XML--做rss訂閱

用的商城項目的表,xml的 rss裏沒加上地址


就是建一個xml文件,但是能導入有商品信息的二維數組,而且要符合rss的條件(有channel節點)


<?php
/*把商城的信息推送
取出最新的十條商品*/
class feed{
	public $template='temp.xml';
	// channel的三個屬性
	public $title="";
	public $link="";
	public $desc="";
// null和空啥區別,上面是要填入字符串;null的這個是對象
	public $dom=null;
	public $rss=null;
	public $goods=array();

	// 創對象;load模板;取rss
	public function __construct(){
		$this->dom=new DomDocument('1.0','utf-8');
		$this->dom->load($this->template);
		// rss必須要item0才能收到,要不然是
		$this->rss=$this->dom->getElementsByTagName('rss')->item(0);
	}

	// 運行方法:channel,商品主體,輸出
	public function display(){
		// 造channel
		$this->createChannel();
		// 造商品
		$this->creategoods($this->goods);

		// 需要echo
		header('content-type:text/xml');
		echo $this->dom->savexml();
	}

	/*創一個節點
	name 節點名 value 裏面的值*/
	public function createEle($name,$value){
		$name=$this->dom->createElement($name);
		$value=$this->dom->createTextNode($value);
		$name->appendChild($value);
		return $name;
	}

	/*創主塊節點,裏面有很多個並列子節點*/
	public function createItem($arr){
		$items=$this->dom->createElement('items');
		foreach ($arr as $k => $v) {
			// 把數組裏的全創成節點
			$item=$this->createEle($k,$v);
			// 再放進item節點裏
			$items->appendChild($item);
		}
		return $items;
	}

	// 造channel,要用到title啊之類的
	public 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('desc',$this->desc));
		return $this->rss->appendChild($channel);
	}

	// 把商品放進rss裏
	public function creategoods($goods){
		foreach ($goods as $good) {
			$good=$this->createItem($good);	
			$this->rss->appendChild($good);
		}

	}
}
$con=mysqli_connect('localhost','root','123456','boolshop');
$sql='select goods_name from goods limit 10';
mysqli_query($con,'set names utf8');

$rs=mysqli_query($con,$sql);
while ($row=mysqli_fetch_assoc($rs)) {
	$list[]=$row;
}

$feed=new feed();
$feed->title='布爾商品推送';
$feed->link='www.sonic.com';
$feed->desc='商品質量好絕無欺瞞';
$feed->goods=$list;

$feed->display();

?>

模板

<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0">
</rss>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章