【问题标题】:php get bing rss feed titles into one varphp 将 bing rss 提要标题放入一个 var
【发布时间】:2012-02-23 23:41:32
【问题描述】:

我正在尝试使用下面的代码来获取一个 bing rss 新闻提要,从该数据中获取所有标题到一个数组中,然后将它们全部内爆,这样我就有一个变量,所有单词都放在一个字符串中,这样我就可以然后用另一个代码创建一个词云。到目前为止,它抓取了 rss 提要和 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);

【问题讨论】:

    标签: php rss foreach simplexml


    【解决方案1】:

    标题位于 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多