PHP xml转数组 数组转xml

  #数组转XML
    private function arrayToXml($array,$root='root'){
        return $this->xml_encode($array, 'utf-8', $root);
    }
    private function xml_encode($array, $charset = 'utf-8', $root){
        $xml = "";/*/'<?xml version="1.0" encoding="' . $charset .'"?>';*/
        $xml .= "<{$root}>";
        $xml .= $this->array_to_xml($array);
        $xml .= "</{$root}>";
        return $xml;
    }
    private function array_to_xml($array){
        if(is_object($array)){
            $array = get_object_vars($array);
        }
        $xml = '';
        foreach($array as $key => $value){
            $_tag = $key;
            $_id  = null;
            if(is_numeric($key)){
                $_tag = 'item';
                $_id  = ' id="' . $key . '"';
            }
            $xml .= "<{$_tag}{$_id}>";
            $xml .= (is_array($value) || is_object($value)) ? $this->array_to_xml($value) : ($value);
            $xml .= "</{$_tag}>";
        }
        return $xml;
    }
    
    #XML转数组
    private function xmlToArray($xmlstring,$root='root'){
        return $this->xml_decode($xmlstring,$root);
    }
    private function xml_decode($xml, $root){
        $search = '/<(' . $root . ')>(.*)<\/\s*?\\1\s*?>/s';
        $array  = array();
        if(preg_match($search, $xml, $matches)){
            $array = $this->xml_to_array($matches[2]);
        }

        return $array;
    }
    private function xml_to_array($xml){
        $search = '/<(\w+)\s*?(?:[^\/>]*)\s*(?:\/>|>(.*?)<\/\s*?\\1\s*?>)/s';
        $array  = array ();
        
        if(preg_match_all($search, $xml, $matches)){
            foreach($matches[1] as $i => $key){
                
                $value = $matches[2][$i];
                if(preg_match_all($search, $value, $_matches)){
                    $array[$key] = $this->xml_to_array($value);
                }else{
                    
                    if('ITEM' == strtoupper($key)){
                        $array[] = html_entity_decode(str_replace( array( '<![CDATA[' , ']]>'), array( '' , '' ), $value ));
                    }else{
                        $array[$key] = html_entity_decode(str_replace( array( '<![CDATA[' , ']]>'), array( '' , '' ), $value ));
                    }
                    
                }
                
            }
        }
        return $array;
    }

猜你喜欢

转载自blog.csdn.net/m0_37711659/article/details/81386207