Last active
August 10, 2023 10:36
-
-
Save Thinkscape/6243184 to your computer and use it in GitHub Desktop.
Problem with using json_encode() to transform XML into array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
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.