xml系列(六)------制作RSS订阅器
发布时间:2020-12-16 06:40:03 所属栏目:百科 来源:网络整理
导读:XML数据格式:?xml version="1.0" encoding="utf-8"?rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/"channeltitle优惠信息/titlelinkhttp://localhost/linkdescription这里有最新的优惠信息/descriptionitemtitle诺基亚N98/titledescri
XML数据格式: <?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/"> <channel> <title>优惠信息</title> <link>http://localhost</link> <description>这里有最新的优惠信息</description> <item> <title>诺基亚N98</title> <description>这是诺基亚手机N98</description> </item> <item> <title>三星</title> <description>三星手机</description> </item> </channel> </rss> 连接数据库 数据表如下
建立feed.xml文件 <?xml version="1.0" encoding="utf-8"?> <!-- rss输出模板 用PHP动态输出内容--> <rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/"></rss> 建立feed.php文件 <?php /* 连接数据库,动态生成Rss feed 连接数据库 取最新的10条,输出xml */ class feed{ public $title='';//channel的title public $link='';//channel的link public $description='';//channel的description public $items=array(); public $template='./feed.xml';//xml模板 protected $rss=null; protected $dom=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); } //封装一个方法,用来造item protected function createItem($arr){ $item=$this->dom->createElement('item'); foreach($arr as $k=>$v){ $item->appendChild($this->createEle($k,$v)); } return $item; } //封装addItem方法,把所有的商品增加到RSS里面去 //$list是商品列表,是二维数组 protected function addItem($list){ foreach($list as $goods){ $this->rss->appendChild($this->createItem($goods)); //$this->rss->appendChild($this->createItem($list)); } } //封装一个方法,直接创建如<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','19900801'); mysql_query('set names utf8',$conn); mysql_query('use test'); $rs=mysql_query('select dealer as title,price as description from shop'); $list=array(); while($row=mysql_fetch_assoc($rs)){ $list[]=$row; } /* echo "<pre>"; print_r($list); echo "</pre>"; */ $feed=new feed(); $feed->title='商城'; $feed->link='http://localhost/bool'; $feed->description='这是优惠信息的集合'; $feed->items=$list; $feed->display(); ?>最后效果
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |