Knowledge for the World

Convert XML to JSON in PHP

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.


$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.