用PHP解析googlenewsrss

用PHP解析googlenewsrss,php,rss,Php,Rss,我想用PHP解析Google新闻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->t

我想用PHP解析Google新闻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 />";
}
?>

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

  • 如何获取新闻标题的超链接
  • 因为每个谷歌新闻的页脚都有许多相关的新闻链接(我上面的代码也包括它们)。如何从描述中删除这些内容
  • 我怎样才能得到每一条新闻的图像呢?(谷歌显示每条新闻的缩略图)
  • 谢谢

  • 要获取新闻项目的URL,请使用$item->link
  • 如果相关的新闻链接有一个通用的分隔符,那么可以使用正则表达式来切断它后面的所有内容
  • Google将缩略图HTML代码放在提要的描述字段中。您可以对图像声明的开括号和闭括号之间的所有内容进行正则表达式,以获取其HTML

  • 我建议退房。我曾在几个不同的项目中使用过它,效果非常好(并且将您目前正在处理的所有头痛问题抽象出来)


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

    好了,这正是您在特定情况下需要的:

    <?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>';
    ?>
    

    不值得作为一个新答案发布,但喜鹊是另一个可能的选择。@IvanCachicatari你说它像一个符咒一样工作,你是否设法从RSS获取图像数据?我似乎无法做到,谷歌新闻RSS(至少对我来说)似乎没有图像部分,80x80图像可以在“gstatic”URL下找到,而不是上面答案中的“ggpht”URL。有什么建议吗?干杯。@a如果有一个选择是转到URL并从网站上的HTML获取主图像,gstatic只是一个缩略图谢谢Ivan,我会研究它!
    [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 ...
            )