使用场景: 数据库 查出列表等数据 ,生成 xml文件
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * 数组转XML类库 */ class Createnode { public $doc; //文档对象 //必须要提供一个构造函数,不然CI loader在加载过程中会出现问题。 public function __construct() { $this->doc = new \DomDocument('1.0', 'UTF-8'); $this->doc->formatOutput = true; } /** * @param $doc * @param $name * @param $array * @param string $attr_array 属性 * @return null */ public function arrayToNode($name,$array,$attr_array = array()) { //创建父节点 $node = $this->createNode($name); //循环数组 foreach ($array as $key => $value) { $element = $this->createNode($key); $element->appendChild($this->createValue($value)); $node->appendChild($element); } if(!empty($attr_array)){ $this->addAttribute($node,$attr_array); } return $node; } public function oneToNode($name,$value,$attr_array = array()) { //创建父节点 $node = $this->createNode($name); //循环数组 if(!is_null($value)){ $node->appendChild($this->createValue($value)); } if(!empty($attr_array)){ $this->addAttribute($node,$attr_array); } return $node; } public function createNode($name) { $node = NULL; //如果是字符串,则创建节点 if (!is_numeric($name)) { $node = $this->doc->createElement($name); } else { //如果是数字,则创建默认item节点 $node = $this->doc->createElement('item'); } return $node; } /** * 创建文本节点 * * @param string || bool || integer $value * * @return object (DOMText || DOMCDATASection ); */ private function createValue($value) { $textNode = NULL; //如果是bool型,则转换为字符串 if (true === $value || false === $value) { $textNode = $this->doc->createTextNode($value ? 'true' : 'false'); } else { //如果含有HTML标签,则创建CDATA节点 if (strpos($value, '<') > -1) { $textNode = $this->doc->createCDATASection($value); } else { $textNode = $this->doc->createTextNode($value); } } return $textNode; } public function saveXml($path){ // $dir = './xml/'.date('Ymd').'/'; $path_parts = pathinfo($path); if(!file_exists($path_parts['dirname'])) mkdir($path_parts['dirname'], 0777, true); //必须要 //$xml = $doc->saveXML(); $res = $this->doc->save($path); return $res; } /** * 为节点设置属性 * @param $node * @param $arr */ private static function addAttribute($node,$arr){ if(is_array($arr)){ foreach($arr as $key=>$val){ $node->setAttribute($key,$val); } } } }
类库的使用示例:
public function createSitemap(){ $this->load->library('createnode'); $data = array( array( 'loc'=> 'http://www-test.funsxxx.cn/home', 'priority'=>0.5, 'lastmod'=>'2017-12-13', 'changefreq'=>'weekly' ), array( 'loc'=> 'http://www-test.funsxxxx.cn/product', 'priority'=>0.5, 'lastmod'=>'2017-12-13', 'changefreq'=>'weekly' ) ); $URLSET = $this->createnode->oneToNode('urlset',NULL); //创建orderlist节点数组 $URLLIST = array(); foreach($data as $val){ $URLLIST[] = $this->createnode->arrayToNode('url',$val); } if(is_array($URLLIST) && !empty($URLLIST)) { foreach($URLLIST as $val){ $URLSET -> appendChild($val); } } $this->createnode->doc->appendChild($URLSET); $this->createnode->saveXml('./seo/sitemap.xml'); }