【问题标题】:Parsing Google News RSS with PHP使用 PHP 解析 Google 新闻 RSS
【发布时间】:2011-06-28 19:52:13
【问题描述】:

我想用 PHP 解析 Google News 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. 如何获取每条新闻的图片? (Google 会显示每条新闻的缩略图)

谢谢。

【问题讨论】:

    标签: php rss


    【解决方案1】:

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

    <?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 ...
            )
    

    【讨论】:

    • @IvanCachicatari 你说它就像一个魅力,你是否设法从 RSS 获取图像数据?我似乎无法做到,看来谷歌新闻 RSS(至少对我而言)没有图像部分,可以在“gstatic”网址下找到 80x80 的图像,而不是在答案中看到的“ggpht”网址以上。有什么建议么?干杯。
    • @Aphire 一种选择是转到 URL 并从现场 HTML 获取主图像,gstatic 只是一个缩略图
    • 谢谢伊万,我会调查的!
    【解决方案2】:

    我建议您查看SimplePie。我已经将它用于几个不同的项目,并且效果很好(并且消除了您目前正在处理的所有令人头疼的问题)。

    现在,如果您只是因为想学习如何编写此代码,您可能应该忽略此答案。 :)

    【讨论】:

    【解决方案3】:
    1. 要获取新闻项目的 URL,请使用 $item->link。
    2. 如果相关新闻链接有共同的分隔符,您可以使用正则表达式将其后的所有内容截断。
    3. Google 将缩略图 HTML 代码放在 Feed 的描述字段中。您可以正则表达式输出图像声明的左括号和右括号之间的所有内容,以获取它的 HTML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多