我已经多次使用 php 和 XML,但这种 XML 在开头和结尾都有 Html 标签:
没有到 xml 文件的直接链接,所以我必须使用 file_get_contents()。
我正在使用这个 php 代码:
$url = "https://www.tandildiario.com/suscripcion.php?section=4";
$xml = file_get_contents($url);
$feed = simplexml_load_string($xml);
foreach ($feed->channel->item as $item) {
.....
我尝试不同的事情..大多数错误都是这样的:
警告:simplexml_load_string():实体:第 14 行:解析器错误:实体“oacute”未在 D: 中定义 eader.php 第 37 行
由于原始 XML 不正确(它在描述标签中包含未转义的 HTML),因此您可以在尝试解析它之前修复它。自己添加 CDATA 属性:
$url = "https://www.tandildiario.com/suscripcion.php?section=4";
$xml = file_get_contents($url);
// Add the CDATA tags for the description
$xml = str_replace('<description>', '<description><![CDATA[', $xml);
$xml = str_replace('</description>', ']]></description>', $xml);
$feed = simplexml_load_string($xml);
您可以在加载 XML 之前解码 HTML 实体。
$url = "https://www.tandildiario.com/suscripcion.php?section=5";
$xml = file_get_contents($url);
$feed = simplexml_load_string(html_entity_decode($xml, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, "UTF-8"));
foreach ( $feed->channel->item as $item ) {
echo $item->asXML();
}
更新:
由于这个答案是 7 年前写的,如果
html_entity_decode
已被弃用,则将 null 传递给第二个参数。我已经更新了答案。