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' | |
); |
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
Guzzle uses the following trick to transform xml to array:
Unfortunately this is known to be unreliable and discard attributes or whole nodes. There are several bug reports like this and this practice is generally not recommended.
Here is a demonstration: https://gist.github.com/Thinkscape/6243184
For guzzle this means that using
data => [ 'xmlAttribute' => true ]
will fail most of the times when there's a mixture of attributes and text values in XML (which occurs for some APIs)Note: I'm rewriting
XMLVisitor
to fix that - it should walk through SimpleXMLElement iterator instead of doing this unnecessary conversion between xml<>json<>array.