I am trying to convert xml to json in php. I tried using json_encode. But the result is different in PHP 7.2 and PHP 7.4 environments. See the below examples.
Example 1
$xmlString = '<properties><property name="width">20</property><property name="height">100</property></properties>';
echo json_encode(simplexml_load_string($xmlString));
Output in PHP 7.4: @attributes are there for each respective node
{"property":[{"@attributes":{"name":"width"},"0":"20"},{"@attributes":{"name":"height"},"0":"100"}]}
Output in PHP 7.2: @attributes are not there
{"property":["20","100"]}
Example 2
$xmlString = '<property name="width">20</property>';
echo json_encode(simplexml_load_string($xmlString));
Output in both PHP 7.2 and PHP 7.4 environments: @attributes are there
{"@attributes":{"name":"width"},"0":"20"}
Example 3
$xmlString = '<properties rank="1"><property name="width">20</property></properties>';
echo json_encode(simplexml_load_string($xmlString));
Output in PHP 7.4: @attributes are there for each respective node
{"@attributes":{"rank":"1"},"property":{"@attributes":{"name":"width"},"0":"20"}}
Output in PHP 7.2: @attributes is there only for the parent node
{"@attributes":{"rank":"1"},"property":"20"}
Questions
- Why the json_encode behaviour is different in the above three examples in different environments?
- If I always want the output as given in the PHP 7.2 environment (without @attribute properties even in the PHP 7.4 environment), how should I convert the SimpleXMLElement object to JSON format?