用PHP解析谷歌新闻RSS


Parsing Google News RSS with PHP

我想用PHP解析谷歌新闻rss。我设法运行了这个代码:

<?
$news = simplexml_load_file('http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=n&output=rss');
foreach($news->channel->item as $item) {
    echo "<strong>" . $item->title . "</strong><br />";
    echo strip_tags($item->description) ."<br /><br />";
}
?>

然而,我无法解决以下问题。例如:

  1. 如何获取新闻标题的超链接
  2. 由于每个谷歌新闻的页脚都有许多相关的新闻链接(我上面的代码也包括它们)。如何从描述中删除这些
  3. 我怎样才能获得每条新闻的图片?(谷歌会显示每条新闻的缩略图)

谢谢。

我们开始了,这正是您在特定情况下所需要的:

<?php
$news = simplexml_load_file('http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=n&output=rss');
$feeds = array();
$i = 0;
foreach ($news->channel->item as $item) 
{
    preg_match('@src="([^"]+)"@', $item->description, $match);
    $parts = explode('<font size="-1">', $item->description);
    $feeds[$i]['title'] = (string) $item->title;
    $feeds[$i]['link'] = (string) $item->link;
    $feeds[$i]['image'] = $match[1];
    $feeds[$i]['site_title'] = strip_tags($parts[1]);
    $feeds[$i]['story'] = strip_tags($parts[2]);
    $i++;
}
echo '<pre>';
print_r($feeds);
echo '</pre>';
?>

输出应该是这样的:

[2] => Array
        (
            [title] => Los Alamos Nuclear Lab Under Siege From Wildfire - ABC News
            [link] => http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGxBe4YsZArH0kSwEjq_zDm_h-N4A&url=http://abcnews.go.com/Technology/wireStory?id%3D13951623
            [image] => http://nt2.ggpht.com/news/tbn/OhH43xORRwiW1M/6.jpg
            [site_title] => ABC News
            [story] => A wildfire burning near the desert birthplace of the atomic bomb advanced on the Los Alamos laboratory and thousands of outdoor drums of plutonium-contaminated waste Tuesday as authorities stepped up ...
        )

我建议您查看SimplePie。我已经在几个不同的项目中使用过它,它效果很好(并且消除了你目前正在处理的所有头痛)。

现在,如果你写这段代码只是因为你想学习如何做,你可能应该忽略这个答案。:)

  1. 要获取新闻项目的URL,请使用$item->link
  2. 如果相关新闻链接有一个通用的分隔符,您可以使用regex来截断它之后的所有内容
  3. 谷歌将缩略图HTML代码放在提要的描述字段中。您可以正则表达式出图像声明的开括号和闭括号之间的所有内容,以获得它的HTML