PHP烧制RSS,php制作基于xml的RSS订阅源功能示例

本文实例讲述了php制作基于xml的RSS订阅源功能。分享给大家供大家参考,具体如下:

首先制作一个 RSS 模板,模板的文件名是 feed.xml,代码如下:

再就是用php文件从数据库读取数据并生成 RSS 文件,这里用一个数组模拟从数据库读取的数据:

class Rss{

protected $dom = null;

protected $temp = './feed.xml';

protected $rss = null;

protected $title = '';

protected $desc = '';

protected $link = '';

public function __construct(){

$this->title = '物理学';

$this->desc = '现代物理学';

$this->link = 'http://mysql/rss.php';

$this->dom = new DOMDocument('1.0','utf-8');

$this->dom->load($this->temp);

$this->rss = $this->dom->getElementsByTagName('rss')->item(0);

}

public function feed($arr){

$this->createChannel();

$channel = $this->dom->getElementsByTagName('channel')->item(0);

foreach ($arr as $v){

$channel->appendChild($this->createItem($v));

}

header('content-type:text/xml');

echo $this->dom->savexml();

}

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->desc));

$this->rss->appendChild($channel);

}

protected function createItem($arr){

$item = $this->dom->createElement('item');

foreach($arr as $k => $v){

$item->appendChild($this->createEle($k,$v));

}

return $item;

}

protected function createEle($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 = new Rss;

$rss->feed($arr);

?>

最后在火狐下效果:

be755ed19943aaa950bad010735edbde.png

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

希望本文所述对大家PHP程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值