3

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?
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Looks like the FIX is now doing things correctly, so the suggestion to downgrade does not seem like a viable solution in the long term
Thank you very much for the prompt response. It seems I have to go for your last solution (wrap the simplexml_load_string() call in another function)
@RiggsFolly Agreed, sorry, was more intending to put it out there as a possible short-term solution until a better one could be written.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.