SimpleXML Attributes to Array SimpleXML Attributes to Array arrays arrays

SimpleXML Attributes to Array


a more elegant way; it gives you the same results without using $attributes[ '@attributes' ] :

$attributes = current($element->attributes());


Don't directly read the '@attributes' property, that's for internal use. Anyway, attributes() can already be used as an array without needing to "convert" to a real array.

For example:

<?php$xml = '<xml><test><a a="b" r="x" q="v" /></test><b/></xml>';$x = new SimpleXMLElement($xml);$attr = $x->test[0]->a[0]->attributes();echo $attr['a']; // "b"

If you want it to be a "true" array, you're gonna have to loop:

$attrArray = array();$attr = $x->test[0]->a[0]->attributes();foreach($attr as $key=>$val){    $attrArray[(string)$key] = (string)$val;}


You could convert the whole xml document into an array:

$array = json_decode(json_encode((array) simplexml_load_string("<response>{$xml}</response>")), true);

For more information see: https://github.com/gaarf/XML-string-to-PHP-array