Making SimpleXML truly simple using JSON in PHP

JSON_vs_XML
So using SimpleXML in PHP is possibly one of the worst hells of typecasting and data extraction procedures one can encounter, or close to it 🙂 But more the point, you don’t need to walk down that road alone, enter JSON.

In the simplest of ways, this will typically get you something useful:

    $pvar = json_decode ($xml);

 

(Where $xml is a SimpleXML-type object) This returns a “slightly easier to manage” PHP array.

If you want an associative array, do this:

    $pvar = json_decode ($xml, true);

 

To get it back to JSON, you simply use:

    $json = json_encode ($pvar).

 

You may need to handle XML data, but you don’t necessarily need to work with it in XML form inside your application. The above examples may not work fully for you if you have to deal with “foreign” files or clean the input data prior to conversion, but you get the idea.

This is, obviously, obvious to many. It’s a lifesaver for others 🙂

LinkedIn:
www.linkedin.com/pulse/making-simplexml-truly-simple-using-json-php-joaquim-homrighausen

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.