SimpleXML Attributes to Array

mseancole picture mseancole · Jul 11, 2012 · Viewed 26.2k times · Source

Is there any more elegant way to escape SimpleXML attributes to an array?

$result = $xml->xpath( $xpath );
$element = $result[ 0 ];
$attributes = (array) $element->attributes();
$attributes = $attributes[ '@attributes' ];

I don't really want to have to loop through it just to extract the key/value pair. All I need is to get it into an array and then pass it on. I would have thought attributes() would have done it by default, or at least given the option. But I couldn't even find the above solution anywhere, I had to figure that out on my own. Am I over complicating this or something?

Edit:

I'm still using the above script until I know for sure whether accessing the @attributes array is safe or not.

Answer

silverskater picture silverskater · Dec 3, 2012

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

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