How to Convert XML to JSON in PHP

How to Convert XML to JSON in PHP
Jeremy Jeremy (10)
Total time: 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:

58 guides
27 guides
8 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.