【问题标题】:How to read this XML with that has HTML tags with PHP?如何用 PHP 读取带有 HTML 标签的 XML?
【发布时间】:2017-07-23 21:44:49
【问题描述】:

我曾多次使用 php 和 XML,但这种 XML 在开头和结尾都有 Html 标签:

Link To XML

没有直接链接到 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' 未在第 37 行的 D:\reader.php 中定义

【问题讨论】:

  • 那个 XML 不正确。如果您要在 XML 中保存 HTML 数据,则应将其包装在 CDATA 标记中。否则,解析器将尝试将 HTML 解析为 XML。 XML 来自哪里?
  • 来自报纸……不是我的,我只需要解析它。
  • 请在问题本身中包含您需要解析的内容的最小示例,而不是作为外部来源的链接。

标签: php xml rss


【解决方案1】:

由于原始 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);

【讨论】:

    【解决方案2】:

    您可以在加载 XML 之前解码 HTML 实体。

    $url = "https://www.tandildiario.com/suscripcion.php?section=5";
    $xml = file_get_contents($url);
    
    $feed = simplexml_load_string(html_entity_decode($xml, null, "UTF-8"));
    
    foreach ( $feed->channel->item as $item )   {
        echo $item->asXML();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2021-12-14
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多