2010-06-19 95 views
0

我已經使用這個PHP來迎接我的博客的最新帖子:使用php獲取wordpress的最新博客文章?

function read_rss($display=0,$url='') { 
    $doc = new DOMDocument(); 
    $doc->load($url); 
    $itemArr = array(); 

    foreach ($doc->getElementsByTagName('item') as $node) { 
     if ($display == 0) { 
      break; 
     } 

     $itemRSS = array (
      'title'  => $node->getElementsByTagName('title')->item(0)->nodeValue, 
      'description' => $node->getElementsByTagName('description')->item(0)->nodeValue, 
      'link'  => $node->getElementsByTagName('link')->item(0)->nodeValue, 
     ); 

     array_push($itemArr, $itemRSS); 

     $display--; 
    } 
    return $itemArr; 
} 

我得知這一關的教程,因爲我不知道怎麼做這個任務。但是它的工作原理,但我不斷收到這個錯誤在我的錯誤日誌打印:

[12-Jun-2010 06:13:36] PHP Warning: DOMDocument::load() [<a href='domdocument.load'>domdocument.load</a>]: Document is empty in http://www.prettyklicks.com/blog/?feed=rss2, line: 1 in public_html/includes/functions.php on line 153 
[12-Jun-2010 06:13:36] PHP Warning: DOMDocument::load() [<a href='domdocument.load'>domdocument.load</a>]: Start tag expected, '&lt;' not found in http://www.prettyklicks.com/blog/?feed=rss2, line: 1 in public_html/includes/functions.php on line 153 

任何想法?

謝謝!

+0

什麼是第16行的public_html/portfolio.php和第79行的public_html/includes/functions.php? – 2010-06-19 17:06:02

+0

抱歉,實際上與錯誤沒有任何關係,我編輯了!原始問題 – 2010-06-27 12:52:39

回答

0

我有同樣的問題,這裏的解決方案:

將行:

$ doc->負載($網址);

$ doc-> loadXML的(的preg_replace( 「/> \ S + <」,的file_get_contents($ URL)));

這樣做是將url加載到一個字符串中,去掉標籤之間的所有空白,然後將它傳遞給DOMDocument對象進行加載。

爲什麼空白很重要?我不確定,但似乎WordPress的RSS提要包含空白,使其很好地縮進,但這干擾了DOMDocument的解析器,並使它看起來像有一個缺少標籤。

貸款到http://netweblogic.com/php/domdocument-whitespace-php/我找到了答案;他們針對不同的情況解決相同的問題。

奇怪的是(我沒有得到這個),我的代碼在我的開發服務器上沒有解決方法,但在生產服務器上沒有解決方法。我不知道爲什麼,但它必須與版本&配置Apache/PHP/WordPress有關。

無論如何,我希望這會有所幫助,而且還不算太遲!

Paul。

+0

除了代碼需要進行一些調整外,您的建議很有用。您缺少preg_replace中的參數和模式中的分隔符。但是,謝謝你,工作得很好! – 2010-09-26 14:04:37