Edit report at http://bugs.php.net/bug.php?id=54632&edit=1
ID: 54632 Comment by: felipecg00 at gmail dot com Reported by: enrico at zimuel dot it Summary: json_encode() doesn't convert SimpleXML data properly Status: Open Type: Bug Package: JSON related Operating System: Ubuntu Linux 10.04 PHP Version: 5.3.6 Block user comment: N Private report: N New Comment: Looks like the problem is not the json_encode. var_dump( $simpleXML ); object(SimpleXMLElement)#1 (1) { ["b"]=> object(SimpleXMLElement)#2 (1) { ["@attributes"]=> array(1) { ["id"]=> string(3) "foo" } } } Where is bar? This is the behavior of SimpleXML. You can try using DOMDocument: $dd = new DOMDocument(); $dd->loadXML('<?xml version="1.0" encoding="UTF-8" ?><a><b id="foo"/>bar</a>'); echo $dd->documentElement->textContent; // outputs bar Still, you can force the SimpleXMLElement to be a string, so it will contain the text inside the node: $bar = (string) $simpleXML; echo $bar; // outputs 'bar' And yet, there is dom_import_simplexml(), which converts a SimpleXML node into a DOMDocument node. But that i've never used before. I think the right thing to do is to keep the text inside text-only nodes. Previous Comments: ------------------------------------------------------------------------ [2011-04-29 13:42:27] enrico at zimuel dot it Description: ------------ I tried to encode the following XML document in JSON using json_encode() and the result doesn't reflect the XML structure. XML document: <?xml version="1.0" encoding="UTF-8" ?> <a><b id="foo"/>bar</a> Result of json_encode(): {"b":{"@attributes":{"id":"foo"}}} The JSON results lost the "bar" value of the XML document. This is the source code that is used: <?php $xml='<?xml version="1.0" encoding="UTF-8" ?><a><b id="foo"/>bar</a>'; $simpleXML= simplexml_load_string($xml); echo json_encode($simpleXML); Test script: --------------- $xml='<?xml version="1.0" encoding="UTF-8" ?><a><b id="foo"/>bar</a>'; $simpleXML= simplexml_load_string($xml); echo json_encode($simpleXML); Expected result: ---------------- It's not obviuos the correct JSON rappresentation of the above XML document. In my opinion it can be as follow: {"a":[{"b":{"@attributes":{"id":"foo"}}},"bar"]} Where the value "bar" is included in a JSON array using the syntax [...] Actual result: -------------- {"b":{"@attributes":{"id":"foo"}}} ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/bug.php?id=54632&edit=1