什么是RSS源?看到这片文章的人相信都知道。自己博客首页不就是一个吗?
好吧,先来一个简单点的。直接就是死代码:详细如何使用就看RSS使用标准吧!
<?xml version = "1.0" encoding = "utf-8"?>
<rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/">
<channel>
<title>
优惠信息
</title>
<link>
http://localhost/test/01.php
</link>
<description>
这里有最新优惠信息
</description>
</channel>
<item>
<title>
优惠信息1
</title>
<description>
这里有最新优惠信息1
</description>
</item>
<item>
<title>
优惠信息1
</title>
<description>
这里有最新优惠信息1
</description>
</item>
</rss>
效果:再火狐浏览器和ie显示正常,再google上显示不太好
这个简答实现了。来个复杂的吧,动态生成RSS
RSS模板
<?xml version="1.0" encoding="utf-8"?>
<!-- rss输出模板 用PHP动态制造channel,和item -->
<rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/"></rss>
动态生成:
<?php
/***
====笔记部分====
连接数据库,动态生成Rss feed
连数据库,取最新的10条商品,输出XML feed
***/
class feed {
public $title = ''; // channel的title
public $link = ''; // channel的link
public $description = ''; // channel的descrition;
public $items = array();
public $template = './feed.xml'; //xml模板
protected $dom = null;
protected $rss = null;
public function __construct() {
$this->dom = new DomDocument('1.0','utf-8');
$this->dom->load($this->template);
$this->rss = $this->dom->getElementsByTagName('rss')->item(0);
}
// 调用createItem,把全部的item节点都生成,再输出
public function display() {
$this->createChannel();
$this->addItem($this->items);
header('content-type: text/xml');
echo $this->dom->savexml();
}
// 封装createChannel方法,用来创建Rss的唯一且必须的channel节点
protected function createChannel() {
$channel = $this->dom->createElement('channel');
$channel->appendChild($this->createEle('title',$this->title));
$channel->appendChild($this->createEle('link',$this->link));
$channel->appendChild($this->createEle('description',$this->description));
$this->rss->appendChild($channel);
}
// 封装addItem方法,把全部的商品添加到RSS里面去
// $list是商品列表,是二维数据,每一行是一个商品
protected function addItem($list) {
foreach($list as $goods) {
$this->rss->appendChild($this->createItem($goods));
}
}
// 封装一个方法,用来造item 比方link description等等
protected function createItem($arr) {
$item = $this->dom->createElement('item');
foreach($arr as $k=>$v) {
$item->appendChild($this->createEle($k,$v));
}
return $item;
}
// 封装一个方法,直接创建开如 <ele>some text</ele>这种节点
protected function createEle($name,$value) {
$ele = $this->dom->createElement($name);
$text = $this->dom->createTextNode($value);
$ele->appendChild($text);
return $ele;
}
}
$conn = mysql_connect('localhost','root','');
mysql_query('set names utf8',$conn);
mysql_query('use test');
$sql = 'select ver as title,content as description from smth order by id desc limit 8';
$rs = mysql_query($sql,$conn);
$list = array();
while($row = mysql_fetch_assoc($rs)) {
$list[] = $row;
}
$feed = new feed();
$feed->title = '布尔商城';
$feed->link = 'http://localhost/bool';
$feed->description = '这是商城的优惠信息集合';
$feed->items = $list;
$feed->display();
生成效果。并查看源代码: