什么是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模板
动态生成:
- <?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();
生成效果,并查看源码: