将数组转化为XML数据

/* Author: 杨宇  [email protected] */

/*

用法示例:

$cls_xml = new cls_xml();

if ($array){
 $cls_xml->array2xml($array);
 echo $cls_xml->getXml(); 
}else{
 echo '';
}

*/

 

class cls_xml{
        var $xml;
        public function array2xml($array,$encoding='gb2312'){
                $this->xml = '<?xml version="1.0" encoding="'.$encoding.'"?><list>';
                $this->xml.= $this->_array2xml($array).'</list>';

        }
        public function getXml(){
                return $this->xml;
        }
        public function _array2xml($array){
                $xml = '';
    foreach($array as $key => $val){
                        is_numeric($key)  &&  $key = "item id=/"$key/"";
                        $xml. = "<$key>";
                        $xml. = is_array($val) ? $this->_array2xml($val) : $this->_cdata($val);
                        list($key,) = explode(' ',$key);
                        $xml. = "</$key>";
                }
                return $xml;
        }
  public function _cdata($str){
   $pos = strpos($str, '<');
   if ($pos !== false) $str = '<![CDATA['.$str.']]>';
   return $str;

  }

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/yangyu112654374/archive/2009/12/25/5073293.aspx

你可能感兴趣的:(将数组转化为XML数据)