用的商城项目的表,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>