Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active August 10, 2023 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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'
);
@Thinkscape
Copy link
Author

Guzzle uses the following trick to transform xml to array:

$xml = new \SimpleXMLElement('<some><xml></xml></some>');
$array = json_decode(json_encode($xml), true);

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.

@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