xml系列(六)------制作RSS订阅器

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();
?>
最后效果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值