Convert JSON to XML using PHP

April 19, 2014 | Last tested: May 2015 | 4797 views | Comments

Barely five steps to convert a JSON file to an XML file with php. The main idea is to read the JSON file, decode it's data, create an XML object, loop through the decoded data and add each record to the created XML object, and set the header content-type if generating the XML on the fly before printing the XML data, or saving the XML data into a new file.

For example.

The objective is to create an XML file with the same format as the screenshot below, which is from the tutorial Create an XML file with PHP.

Please mouse over here to view the image.

Convert an existing JSON file to XML in PHP on the fly.

//read the JSON file
$jsonFile = file_get_contents('members.json');

//decode the data
$jsonFile_decoded = json_decode($jsonFile);

//create a new xml object
$xml = new SimpleXMLElement('<members/>');

//loop through the data, and add each record to the xml object
foreach($jsonFile_decoded AS $members){
	foreach($members AS $memberDetails){
		$member = $xml->addChild('member');
		$member->addChild('lastName', $memberDetails[0]);
		$member->addChild('firstName', $memberDetails[1]);
		$member->addChild('age', $memberDetails[2]);
		$member->addChild('sex', $memberDetails[3]);
		$member->addChild('location', $memberDetails[4]);
	}
}

//set header content type
Header('Content-type: text/xml');

//output the xml file
print($xml->asXML());

 

To save the generated XML data to a file with a name members.xml.

  1. Remove the line where the Content-type was set.
    //remove the line below
    Header('Content-type: text/xml');
    
  2. Change this.
    print($xml->asXML());
    To this.
    $xml->asXML("members.xml");

Result:

Please mouse over here to view the image.