前面说到了给博客添加RSS功能,现在来说一下RSS实现原理。
什么是RSS?百度百科是这么说的。
原理就是通过一个数据库查询语句,获取最新志信息用于循环输出,并且由php生成xml的格式,然后输出。
代码如下:
PHP代码
- require('db_config.php');
- mysql_connect($db_host, $db_user, $db_pwd);
- mysql_select_db($db_name);
- mysql_query("set names utf8");
- $result = mysql_query("select * from `blog` order by `Id` desc limit 0,8");
- $blogurl = "http://".$_SERVER["HTTP_HOST"];
- header("Content-type:application/xml");
- $d_rss = "";
- $d_rss.="<?xml version=/"1.0/" encoding=/"utf-8/"?>/r/n";
- $d_rss.="<rss version=/"2.0/">/r/n";
- $d_rss.="<channel>/r/n";
- $d_rss.="<title>追梦 - WuLeilei's Blog</title>/r/n";
- $d_rss.="<link>$blogurl</link>/r/n";
- $d_rss.="<description>WuLeilei's Blog</description>/r/n";
- $d_rss.="<language>zh-cn</language>/r/n";
- $d_rss.="<generator>$blogurl</generator>/r/n";
- while($row = mysql_fetch_array($result)){
- $d_rss.="<item>/r/n<title>".$row["BlogTitle"]."</title>/r/n<link>".$blogurl."/index.php/Blog/details/id/".$row["BlogId"].".html</link>/r/n<description><![CDATA[".strip_tags($row["BlogContent"])."]]></description>/r/n<pubDate>".date('r', strtotime($row['BlogAddTime'])+16*3600)."</pubDate>/r/n</item>/r/n";
- }
- $d_rss.="</channel>/r/n</rss>";
- echo $d_rss;
然后在页面的<head>与</head>标签之间加入如下代码:
XML/HTML代码
- <link rel="alternate" type="application/rss+xml" title="RSS 2.0 - 所有文章" href="http://www.wuleilei.com/Public/rss.php" />
在到页面合适的地方加一个RSS的链接即可。效果如下:http://www.wuleilei.com/Public/rss.php