php总结 --- 10. xml操作

时间:2022-08-05 17:39:06

xml 和array互换

 /**
  * 数组编码为XML
  * @param array $data 数据
  * @return mixed 编码后数据
  */
 function xmlencode($data){
     $xml = new \SimpleXMLElement('<xml></xml>');
     arrayToXml($xml, $data);
     return $xml->asXML();
 }

 /**
  * XML转换为数组
  * @param string $xml XML数据
  */
 function xmldecode($xml){
     $xml = new \SimpleXMLElement($xml);
     $data = array();
     foreach($xml as $key => $value){
         $data[$key] = strval($value);
     }
     return $data;
 }

 /**
  * 数组转换XML
  * @param object $xml XML对象
  * @param array $data 数据
  * @param string $item Item
  */
 function arrayToXml($xml, $data, $item = 'item'){
     foreach($data as $key => $value){
         is_numeric($key) && $key = $item;

         if(is_array($value) || is_object($value)){
             $child = $xml->addChild($key);
             arrayToXml($child, $value, $item);
         }else{
             if(is_numeric($value)){
                 $child = $xml->addChild($key, $value);
             }else{
                 $child = $xml->addChild($key);
                 $node = dom_import_simplexml($child);
                 $cdata = $node->ownerDocument->createCDATASection($value);
                 $node->appendChild($cdata);
             }
         }
     }
 }

toXml

 public static function toXml($array){
         $xml = '<xml>';
         forEach($array as $k=>$v){
             $xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';
         }
         $xml.='</xml>';
         return $xml;
     }

toarr

 public static function parseXML($xmlSrc){
         if(empty($xmlSrc)){
             return false;
         }
         $array = array();
         $xml = simplexml_load_string($xmlSrc);
         $encode = Utils::getXmlEncode($xmlSrc);

         if($xml && $xml->children()) {
             foreach ($xml->children() as $node){
                 //有子节点
                 if($node->children()) {
                     $k = $node->getName();
                     $nodeXml = $node->asXML();
                     $v = substr($nodeXml, strlen($k)+, strlen($nodeXml)-*strlen($k)-);

                 } else {
                     $k = $node->getName();
                     $v = (string)$node;
                 }

                 if($encode!="" && $encode != "UTF-8") {
                     $k = iconv("UTF-8", $encode, $k);
                     $v = iconv("UTF-8", $encode, $v);
                 }
                 $array[$k] = $v;
             }
         }
         return $array;
     }

获取xml编码

 function getXmlEncode($xml) {
         $ret = preg_match ("/<?xml[^>]* encoding=\"(.*)\"[^>]* ?>/i", $xml, $arr);
         if($ret) {
             ] );
         } else {
             return "";
         }
     }