2012-07-23 140 views
0

我有下面的代码在一个XML文件中读取:使用simplexml_load_file问题

$xml2 = simplexml_load_file('http://www.facebook.com/feeds/page.php?format=rss20&id=334704593230758'); 
$item = $xml2->channel->item; 

我正在以下回到我的源代码:

<b>Warning</b>: simplexml_load_file() [<a href='function.simplexml-load-file'>function.simplexml-load-file</a>]: http://www.facebook.com/feeds/page.php?format=rss20&amp;id=334704593230758:11: parser error : xmlParseEntityRef: no name in <b>/home/content/49/8644249/html/test/_inc/footer.php</b> on line <b>110</b><br /> 


继续上就像那10条线一样。 xml代码有问题吗?

+0

快速谷歌(你可以做)显示,这意味着该文件中的未编码符号(所有流浪'&'应该是'&') 。看起来Facebook不会正确输出html_entities()d RSS feed。 – 2012-07-23 21:44:12

+0

Ooooh有人在FB会得到一个屁股踢...虽然我正在检查当前由该URL返回的XML,并没有这样的问题 - 它有几个正确编码的实体。 – DaveRandom 2012-07-23 21:46:05

回答

2

好吧,有点古怪,因为这是一个RSS源,并不是直接可读的,所以答案就是您必须在请求中包含User-Agent:标题。

当我在Chrome中加载URL时,获得有效的XML文档,当我运行代码时,我得到的错误与您所做的相同。仔细观察后,我发现当我运行你的代码时,我实际上得到了一个最小的HTML文档,而不是所需的XML - 为了得到正确的结果,你必须传递一个有效的用户代理字符串,这意味着你不能使用simplexml_load_file()因为它不支持流上下文。

此代码的工作对我来说:

// User-Agent string from Chrome. I haven't tested anything else so I don't know 
// what is actually required, but this works. 
$context = stream_context_create(array(
    'http'=>array(
    'user_agent' => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11' 
    ) 
)); 

// Get data as a string 
$xml2 = file_get_contents('http://www.facebook.com/feeds/page.php?format=rss20&id=334704593230758', FALSE, $context); 

// Convert string to a SimpleXML object 
$xml2 = simplexml_load_string($xml2); 

$item = $xml2->channel->item; 
+0

它效果很好。非常感谢你 – jppower175 2012-07-24 00:08:28