【问题标题】:Remote XML file is poorly written causing parsing errors远程 XML 文件写得不好导致解析错误
【发布时间】:2013-08-11 13:48:54
【问题描述】:

我正在编写一个 RSS 类型的阅读器网页来解析来自一些游戏网站的信息。

其中一个游戏的 RSS 提要写得不好。

他们没有费心将描述包装到 CDATA 中,并且使用 simplexml_load_file 解析时会出错。

这是我为解析它而编写的函数:

 function displayAll($url) {

 $url = "https://www.game.com/newsfeed/rss.vm";
 $game = simplexml_load_file($url);

 $item = $game->rss->channel->item;
 foreach ($item as $items) {

 echo '<li>';
 echo ''.$items->title.'';
 echo ''.$items->description.'';
 echo ''.$items->link.'';
 echo '</li>';

  }
 }

我收到以下错误:

 Warning: simplexml_load_file() [function.simplexml-load-file]: https://www.game.com/newsfeed/rss.xml:15: parser error : 
 Entity 'nbsp' not defined in /results.php on line 27
 Warning: simplexml_load_file() [function.simplexml-load-file]: https://www.game.com/newsfeed/rss.xml:20: parser error : 
 Entity 'nbsp' not defined in /results.php on line 27

获得多个相同的错误都围绕在提要中写得很糟糕的html。

我在问如何解决这个问题,有没有办法在解析之前将 html 转换回 xml 描述中的字母/空格/等标签?

任何建议将不胜感激。

【问题讨论】:

  • 你可以尝试在你知道的东西上做一些正则表达式和替换,然后再将它传递给 simplexml,所以用 curl 将它拉回来,并将其存储为本地 var,然后在传递之后处理它将它转换为 simplexml 它是一只猪,但它的规则而不是例外,来自其他地方的大多数 xml 提要很少(即使来自应该知道更好的大型技术网站!)格式正确。

标签: php xml xml-parsing rss html-parsing


【解决方案1】:

试试这个

$data = file_get_contents($url);
$data = str_replace(array('<description>','</description>'), array('<description><![CDATA[',']]></description>'), $data);

$game = simplexml_load_string($data);

【讨论】:

  • 成功了!没想到要尝试替换描述标签。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多