Pathum Harshana
Pathum Harshana

Reputation: 135

PHP json_encode of SimpleXMLELement gives different results in different environments

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

  1. Why the json_encode behaviour is different in the above three examples in different environments?
  2. 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?

Upvotes: 3

Views: 167

Answers (1)

Matthew Turland
Matthew Turland

Reputation: 763

Looks like this change in behavior happened in 7.3.17 / 7.4.5 (see this example) and was due to a bug fix. You can confirm this in the SimpleXML section of the changelogs for 7.4.5 and 7.3.17.

The easiest way to revert the behavior would probably be to downgrade your PHP version.

It may be possible to use the $options parameter of simplexml_load_string() to change how it behaves. I'd consult the manual page and its comments for more information on that.

That option notwithstanding, you may just have to wrap the simplexml_load_string() call in another function you write that alters its return value to your preference.

Upvotes: 3

Related Questions