php获取bs rss feed标题到一个var

时间:2012-02-23 23:41:33

标签: php rss foreach simplexml

我正在尝试使用下面的代码来获取一个bs rss新闻源,从这个数据中获取所有标题到一个数组,然后将它们全部一起内爆,所以我有一个变量,所有单词都在一个字符串中,所以我可以然后用另一个代码创建一个单词云。到目前为止,它抓住了rss feed和print_r($ doc);如果你取消注释它会显示简单的xml。我的foreach循环以获取数组中的标题似乎不起作用,我无法看到错误在哪里?提前谢谢。

$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);

1 个答案:

答案 0 :(得分:0)

标题位于 rss / channel / item / title ,而不是代码在 rss / entry / title 中查找的位置。除此之外,你获得价值的方式还不错。

$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;

使用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;