2012-02-23 80 views
0

我想用下面的代碼來獲得一個RSS新聞飼料,從數據抓取所有標題到一個數組,然後一起打包它們,所以我有一個變量與所有將這些單詞放在一個字符串中,然後用另一個代碼創建一個字雲。到目前爲止,它抓住了RSS feed和print_r($ doc);如果取消註釋,則顯示簡單的xml。無論我的foreach循環抓取數組中的標題似乎沒有工作,我看不到錯誤在哪裏?提前致謝。PHP獲得bing rss飼料標題到一個變種

$ch = curl_init("http://api.bing.com/rss.aspx?Source=News&Market=en-GB&Version=2.0&Query=web+design+uk"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
$data = curl_exec($ch); 
curl_close($ch); 

$doc = new SimpleXMLElement($data); 
//print_r($doc); 

$vals = array(); 
foreach ($doc->entry as $entry) { 
$vals[] = (string) $entry->title; 
} 

//join content nodes together for the word cloud 
$vals = implode(' ', $vals); 

echo($vals); 

回答

0

標題也被RSS /渠道/項目/標題,而不是在您的代碼看起來對他們來說,在RSS /項/標題。除此之外,您獲取值的方式很好。

$rss = simplexml_load_file('http://api.bing.com/rss.aspx?Source=News&Market=en-GB&Version=2.0&Query=web+design+uk'); 

$titles = array(); 
foreach ($rss->channel->item as $item) { 
    $titles[] = (string) $item->title; 
} 

//join content nodes together for the word cloud 
$words = implode(' ', $titles); 

echo $words; 

一個quicky替代,使用XPath拿到冠軍,是:

$rss = simplexml_load_file('http://api.bing.com/rss.aspx?Source=News&Market=en-GB&Version=2.0&Query=web+design+uk'); 
$words = implode(' ', $rss->xpath('channel/item/title')); 
echo $words;