首先制作一個 RSS 模板,模板的文件名是 feed.xml,代碼如下:
代碼如下 復制代碼<?xmlversion="1.0"encoding="utf-8"?>
<rssversion="2.0"xmlns:wfw="http://wellformedweb.org/CommentAPI/"></rss>
再就是用php文件從數據庫讀取數據並生成 RSS 文件,這裡用一個數組模擬從數據庫讀取的數據:
代碼如下 復制代碼<?php
classRss{
protected$dom= null;
protected$temp='./feed.xml';
protected$rss= null;
protected$title='';
protected$desc='';
protected$link='';
publicfunction__construct(){
$this->title ='物理學';
$this->desc ='現代物理學';
$this->link ='http://mysql/rss.php';
$this->dom =newDOMDocument('1.0','utf-8');
$this->dom->load($this->temp);
$this->rss =$this->dom->getElementsByTagName('rss')->item(0);
}
publicfunctionfeed($arr){
$this->createChannel();
$channel=$this->dom->getElementsByTagName('channel')->item(0);
foreach($arras$v){
$channel->appendChild($this->createItem($v));
}
header('content-type:text/xml');
echo$this->dom->savexml();
}
protectedfunctioncreateChannel(){
$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->desc));
$this->rss->appendChild($channel);
}
protectedfunctioncreateItem($arr){
$item=$this->dom->createElement('item');
foreach($arras$k=>$v){
$item->appendChild($this->createEle($k,$v));
}
return$item;
}
protectedfunctioncreateEle($name,$value){
$e=$this->dom->createElement($name);
$t=$this->dom->createTextNode($value);
$e->appendChild($t);
return$e;
}
}
$arr=array(
array(
'title'=>'牛頓力學',
'link'=>'1',
'description'=>'牛頓力學'
),
array(
'title'=>'相對論',
'link'=>'1',
'description'=>'愛因斯坦的相對論'
)
);
$rss=newRss;
$rss->feed($arr);
?>
最後在火狐下效果: