|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #46309 JSON encode simplexml object loses attributes on leaf nodes
Submitted: 2008-10-16 00:09 UTC Modified: 2008-10-20 23:10 UTC
From: steve at stevegoodwin dot net Assigned:
Status: Not a bug Package: JSON related
PHP Version: 5.2.6 OS: Windows
Private report: No CVE-ID: None
 [2008-10-16 00:09 UTC] steve at stevegoodwin dot net
If you json encode a simplexml object, any xml leaf nodes will lose 
their attributes

The attached script has two small xml strings.  One with attributes 
on the leaf node, one without.

When you run the script, attribute values disappear for the second 
json string 

Reproduce code:
$xml_string1 = '<?xml version="1.0"?><ItemList><Item ID="456"><ExtraTag>ABC</ExtraTag></Item><Item ID="789"><ExtraTag>DEF</ExtraTag></Item></ItemList>';
$xml_string2 = '<?xml version="1.0"?><ItemList><Item ID="456">ABC</Item><Item ID="789">DEF</Item></ItemList>';
$xml_obj = simplexml_load_string($xml_string1);
$json = json_encode($xml_obj);
print "Input XML Document: " . htmlentities($xml_string1) . "<br/>attributes are present:<br/>$json<br/><br/>";

$xml_obj = simplexml_load_string($xml_string2);
$json = json_encode($xml_obj);
print "Input XML Document: " . htmlentities($xml_string2) . "<br/>attributes are <b>Not</b> present:<br/>$json<br/><br/>";

Expected result:
Input XML Document: <?xml version="1.0"?><ItemList><Item 

attributes are present:

Input XML Document: <?xml version="1.0"?><ItemList><Item 
ID="456">ABC</Item><Item ID="789">DEF</Item></ItemList>

attributes are Not present:

Actual result:
json string above labeled with "attributes are present:" is correctly 
json encoded.

json string above labeled with "attributes are Not present:" is 
incorrectly json encoded.  The json object does not have the 
attribute name or values


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2008-10-20 23:10 UTC]
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at and the instructions on how to report
a bug at

You cannot do a lossless (loss of attributes) on an object of a certain 
type such as SimpleXML.
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Tue Dec 05 09:01:27 2023 UTC