Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active August 10, 2023 10:36
Show Gist options
  • Save Thinkscape/6243184 to your computer and use it in GitHub Desktop.
Save Thinkscape/6243184 to your computer and use it in GitHub Desktop.
Problem with using json_encode() to transform XML into array.
<?php
$xml = new \SimpleXMLElement('<xml>
<node attr="bar">second</node>
</xml>');
$array = json_decode(json_encode($xml), true);
print_r($array);
/*
Array
(
[node] => second
)
*/
$expected = array(
'@attributes' => array(
'attr' => 'bar'
),
'second'
);
@Jakobud
Copy link

Jakobud commented Jan 26, 2015

FYI, SimpleXML doesn't discard the attributes. They are there, they just don't print out when using methods like echo, var_dump, print_r, etc. Look at the note on this page:

http://php.net/manual/en/simplexmlelement.attributes.php

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

While parsing the SimpleXML object, you can still access the attributes just fine using $element->attributes().

Attributes missing from var_dump() is definitely misleading though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment