How to convert xml into array in php?

前端 未结 9 1346
半阙折子戏
半阙折子戏 2020-11-22 02:54

I want to convert below XML to PHP array. Any suggestions on how I can do this?


   
     
       

        
9条回答
  •  时光说笑
    2020-11-22 03:15

    Converting an XML string ($buffer) into a simplified array ignoring attributes and grouping child-elements with the same names:

    function XML2Array(SimpleXMLElement $parent)
    {
        $array = array();
    
        foreach ($parent as $name => $element) {
            ($node = & $array[$name])
                && (1 === count($node) ? $node = array($node) : 1)
                && $node = & $node[];
    
            $node = $element->count() ? XML2Array($element) : trim($element);
        }
    
        return $array;
    }
    
    $xml   = simplexml_load_string($buffer);
    $array = XML2Array($xml);
    $array = array($xml->getName() => $array);
    

    Result:

    Array
    (
        [aaaa] => Array
            (
                [bbb] => Array
                    (
                        [cccc] => Array
                            (
                                [ffffdd] => 
                                [eeee] => 
                            )
    
                    )
    
            )
    
    )
    

    If you also want to have the attributes, they are available via JSON encoding/decoding of SimpleXMLElement. This is often the most easy quick'n'dirty solution:

    $xml   = simplexml_load_string($buffer);
    $array = json_decode(json_encode((array) $xml), true);
    $array = array($xml->getName() => $array);
    

    Result:

    Array
    (
        [aaaa] => Array
            (
                [@attributes] => Array
                    (
                        [Version] => 1.0
                    )
    
                [bbb] => Array
                    (
                        [cccc] => Array
                            (
                                [ffffdd] => Array
                                    (
                                        [@attributes] => Array
                                            (
                                                [Id] => id:pass
                                            )
    
                                    )
    
                                [eeee] => Array
                                    (
                                        [@attributes] => Array
                                            (
                                                [name] => hearaman
                                                [age] => 24
                                            )
    
                                    )
    
                            )
    
                    )
    
            )
    
    )
    

    Take note that all these methods only work in the namespace of the XML document.

提交回复
热议问题