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.
You could convert the whole xml document into an array:
For more information see: https://github.com/gaarf/XML-string-to-PHP-array
I think you will have to loop through. You can get it into array once you read xml.
a more elegant way; it gives you the same results without using $attributes[ '@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:
If you want it to be a "true" array, you're gonna have to loop:
For me below method worked
This also provides me all the attributes as well, which I didn't get from any other method.