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

前端之家收集整理的这篇文章主要介绍了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();
?>
最后效果

原文链接:https://www.f2er.com/xml/297851.html

猜你在找的XML相关文章