Search code examples
phpxmlsimplexml

Converting multidimensional SimpleXML to associative array


I have a nested multidimensional XML string that I get into SimpleXML. I want to convert it into an associative array. The examples listed on php.net do not work correctly or they do only for flat xmls.


Solution

  • This works better than the example on SimpleXML manual page, but in its current form it discards the attributes.

    function xml2array($xmlObject, $out = array())
    {
        foreach ($xmlObject as $node) {
            if ($node->count() > 0) {
                $out[$node->getName()][] = xml2array($node);
            } else {
                $out[$node->getName()] = (string)$node;
            }
        }
        return $out;
    }