note 103306 deleted from book.simplexml by danbrown

From: Date: Wed, 06 Apr 2011 14:16:24 +0000
Subject: note 103306 deleted from book.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-178563@lists.php.net to get a copy of this message
Note Submitter: marcus dot garcia at uol dot com dot br ---- Revised version, as i've got a comment pointing out a bug (in fact even in my post the bug was there and i didn't see, the very first attribute key was being discarded): function xml2array($xml) { if(get_class($xml) != 'SimpleXMLElement') { $xml = simplexml_load_string($xml); } if(!$xml) { return false; } $main = $xml->getName(); $arr = array(); $nodes = $xml->children(); foreach($nodes as $node) { $nodeName = $node->getName(); $nodeAttributes = $node->attributes(); $attributesArray = array(); foreach($nodeAttributes as $attributeName => $attributeValue) { $attributesArray[$attributeName] = (string) $attributeValue; } $nodeValue = sizeOf($node->children()) == 0 ? trim($node) : xml2array($node); if(!isSet($arr[$nodeName]['value'])) { $arr[$nodeName]['value'] = $nodeValue; } else { if(!is_array($arr[$nodeName]['value'])) { $arr[$nodeName]['value'][] = array_shift($arr[$nodeName]); } $arr[$nodeName]['value'][] = $nodeValue; } $arr[$nodeName]['attributes'][] = $attributesArray; } return($arr); }

« previous php.notes (#178563) next »