您的位置:首页 > 运维架构 > 网站架构

用PHP生成RSS Feed,并给网站添加RSS Feed功能

2010-07-15 10:47 375 查看
给网站添加 RSS Feed 功能能带来很多好处。如果你用的是 PHP,你可以写代码自己生成,详细方法可以参考 IBM 网站的这篇文章:PHP and RSS: Getting it together

当然网上也有现成的代码可以使用,想必这也是大多数人喜欢的方式,比如这个 FeedCreator,是一个用 PHP 生成 RSS Feed 的通用类,支持 RSS 0.91、RSS 1.0、RSS 2.0、PIE 0.1、MBOX、OPML 1.0、ATOM、ATOM 0.3 和自定义的 HTML 和 JS 等多种 RSS 格式。FeedCreator 使用很简单,他的网站上有详细的使用说明和例子。

网站:FeedCreator.class.php
下载源代码:FeedCreator_172.zip
查看源代码:View FeedCreator Source

只要按照网站的例子和源码上的说明,在几分钟之内就可以给网站生成 RSS Feed,但 FeedCreator 在 PHP5 下运行时会出现以下错误(PHP4 正常):

XML解析错误:废弃 document 元素之后的内容
位置:http://www.faceker.com/rss/
行:3,列:1<b>Notice</b>: Undefined property: RSSCreator20::$cssStyleSheet in
<b>E:/My/Web/rss/feedcreator.class.php</b> on line <b>591</b><br />


如果你也遇到了以上错误,请查看官方论坛的这篇贴子对源码做一下小改动即可。

如果你的文章中有中文,生成的 RSS Feed 都会是乱码,并且时间也和实际不相符或者显示为一个 1970-01-01 值,这是由于未设置正确编码方式和时区所造成的。

搜索源码中的所有 var $encoding = “ISO-8859-1″,将编码格式改为 GBK;搜索 define(”TIME_ZONE”,”+01:00″) 改为 +8:00 或其它时区格式,并且在给 RSS 条目赋时间时用 strtotime() 函数将日期字符串转换为时间格式,这样就不会造成显示 1970 年的问题。

RSS Feed 生成后,如何设置才能给网站添加 RSS 呢?并且让 Firefox、IE7 或其它 Feed 机器人自动发现?很简单,在网页的 Head 节添加一个特定的 Link 标签即可,如下:

<link rel=”alternate” type=”application/rss+xml” title=”一个人去流浪 RSS Feed” href=”http://feed.feedsky.com/faceker” />

设置 title 为 Feed 标题,href 为 Feed 地址,一切就 OK 了!

Example for building an RSS 1.0 feed:
<?
include("feedcreator.class.php");

$rss = new UniversalFeedCreator();
$rss->useCached();
$rss->title = "PHP news";
$rss->description = "daily news from the PHP scripting world";
$rss->link = "http://www.dailyphp.net/news";
$rss->syndicationURL = "http://www.dailyphp.net/".$PHP_SELF;

$image = new FeedImage();
$image->title = "dailyphp.net logo";
$image->url = "http://www.dailyphp.net/images/logo.gif";
$image->link = "http://www.dailyphp.net";
$image->description = "Feed provided by dailyphp.net. Click to visit.";
$rss->image = $image;

// get your news items from somewhere, e.g. your database:
mysql_select_db($dbHost, $dbUser, $dbPass);
$res = mysql_query("SELECT * FROM news ORDER BY newsdate DESC");
while ($data = mysql_fetch_object($res)) {
$item = new FeedItem();
$item->title = $data->title;
$item->link = $data->url;
$item->description = $data->short;
$item->date = $data->newsdate;
$item->source = "http://www.dailyphp.net";
$item->author = "John Doe";

$rss->addItem($item);
}

$rss->saveFeed("RSS1.0", "news/feed.xml");
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: