2012-02-24 37 views
1

我一直在使用下面的代码在谷歌新闻拉,但是,我需要有最终结果在网站上是一个实际的RSS提要,以便其他人可以抢进。现在输出创建一个不错的index.php页面。这很好,但不符合我的目的。 SimplePie可以创建一个被格式化为rss输出的页面用于抓取目的吗?捆绑RSS在电子邮件

谢谢你提前。


<?php 

// Make sure SimplePie is included. You may need to change this to match the location of simplepie.inc. 
require_once('simplepie.inc'); 

// We'll process this feed with all of the default options. 
$feed = new SimplePie(); 

// Set the feed to process. 
$feed->set_feed_url('http://news.google.com/news?hl=en&gl=us&q=new+york+commercial+real+estate&ie=UTF-8&output=rss'); 

// Run SimplePie. 
$feed->init(); 

// This makes sure that the content is sent to the browser as text/html and the UTF-8 character set (since we didn't change it). 
$feed->handle_content_type(); 

// Let's begin our XHTML webpage code. The DOCTYPE is supposed to be the very first thing, so we'll keep it on the same line as the closing-PHP tag. 
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
     "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
    <title>Sample SimplePie Page</title> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 

</head> 
<body> 

     <div class="header"> 
     <h2><a href="<?php echo $feed->get_permalink(); ?>"><?php echo $feed->get_title(); ?></a></h2> 
     <p><?php echo $feed->get_description(); ?></p> 
    </div> 

    <?php 
    /* 
    Here, we'll loop through all of the items in the feed, and $item represents the current item in the loop. 
    */ 
    foreach ($feed->get_items() as $item): 
    ?> 

     <div class="item"> 
      <h4><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4> 
      <p><?php echo $item->get_description(); ?></p> 
      <p><small>Posted on <?php echo $item->get_date('j F Y | g:i a'); ?></small></p> 
     </div> 

    <?php endforeach; ?> 

</body> 
</html> 
+0

仅供参考,我相信在你所描述的侵犯了他们的服务条款的方式重新包装谷歌新闻。 – Brad 2012-02-24 05:05:54

回答

0

使用了SimplePie只用于分析阶段,你需要编写自己的代码来输出作为RSS。

你可以做到这一点的快速和肮脏的方式:

<?xml version="1.0" encoding="UTF-8" ?> 
<rss version="2.0"> 
    <channel> 
     <title>Your Site</title> 

<?php 
     foreach ($feed->get_items() as $item): 
?> 
     <entry> 
      <title><?php echo $item->get_title() ?></title> 
      <description><?php echo $item->get_content() ?></description> 
      <!-- ... --> 
     </entry> 
    </channel> 
</rss> 

一个更好的方法是使用SimpleXML来创建元素,然后输出的结果。这将确保您的XML格式正确,并且所有内容都能正确转义。

但是,你也有这样的时候,布拉德提到要小心的服务条款。您应该至少确保正确的归属。

+0

谢谢,我非常关心违反任何服务条款。我看过他们的服务条款,似乎如果你确保适当的归属,它不会是一个问题,但我肯定在这个开放的讨论,因为它似乎有点不清楚。至于代码片段,感谢您的建议,我会试一试。 – 2012-02-24 13:55:32

+0

关于快速和简单的由Ryan提供 - 是将被集成到或者了SimplePie无关的代码完全从分离了SimplePie代码?我看到了$用品 - > get_title()看起来像图书馆了SimplePie代码,并可以找到没有提及供稿网址。谢谢。 – 2012-02-24 14:15:25

+0

该代码会在您想要输出Feed的任何位置执行。在上面的例子中,它替换了“让我们开始我们的XHTML网页代码”之后的所有内容。这也只是一个非常快速的例子,一个完整的feed会包含更多的信息,但这只是SimplePie方法匹配标签的一个例子。 – 2012-02-25 13:07:43