How to Convert XML to JSON in PHP

John John (304)
5 minutes

Converting XML files to JSON is a good practice for providing easy manipulation and preparing service responses. You can accomplish this efficiently with just three lines of code.

Posted in these interests:
h/webdev60 guides
h/javascript27 guides
h/php8 guides
$xml = simplexml_load_string($xml_string); // where $xml_string is the XML data you'd like to use (a well-formatted XML string). If retrieving from an external source, you can use file_get_contents to retrieve the data and populate this variable.
$json = json_encode($xml); // convert the XML string to JSON
$array = json_decode($json,TRUE); // convert the JSON-encoded string to a PHP variable

This method discards XML attributes; for example:

<fictitiousCharacter type="scientist">Doc Brown</fictitiousChracter>

.. is interpreted as:


This is normally not a problem as most well-formatted XML files use nesting to specify important attributes; however, if you wish to preserve these XML attributes, you'll need to write a more elaborate solution that moves these attributes prior to converting to JSON.

The lastest OS for the iPhone...
Zach Zach (248)
1 minute

Honestly, it's quite impressive just how substantial this iOS update is from Apple. It makes the experience much more intuitive and user-friendly.