Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: json_decode(json_encode($xml));

Tags:

php

I was reading some code and saw the following line

 $obj = json_decode(json_encode($xml));

$xml is from simplexml_load_string so to me it looks like that the line is equivalent of

$obj = $xml;

What might be reason for the seemingly unnecessary encoding and decoding?

like image 859
Tero Lahtinen Avatar asked Mar 10 '23 19:03

Tero Lahtinen


1 Answers

If $xml is a SimpleXml object, you can't access some of its attributes directly. It's a trick that is used to convert SimpleXml object to a classical object and get access to all of its attributes :)

Also, you can pass a boolean parameter to get an array instead of an object: json_decode(json_encode($xml), true);

like image 187
Fky Avatar answered Mar 25 '23 00:03

Fky