這篇文章主要介紹了php製作基於xml的RSS訂閱源功能,結合執行個體形式分析了RSS訂閱源檔案產生類的定義與使用方法,需要的朋友可以參考下
本文執行個體講述了php製作基於xml的RSS訂閱源功能。分享給大家供大家參考,具體如下:
首先製作一個 RSS 模板,模板的檔案名稱是 feed.xml,代碼如下:
<?xml version="1.0" encoding="utf-8"?><rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/"></rss>
再就是用php檔案從資料庫讀取資料並產生 RSS 檔案,這裡用一個數組類比從資料庫讀取的資料:
<?php 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);?>
最後在Firefox下效果:
以上就是本文的全部內容,希望對大家的學習有所協助。