2012-07-23 139 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