Convert XML to JSON in PHP

April 12, 2014 | Last tested: May 2015 | 1477 views | Comments

Load the XML file, format according to the requirement, encode to a JSON format, and generate or save the JSON file. That's four simple steps to convert an XML file to a JSON file using PHP.

For example.

The goal is to generate a JSON file similar to the file created on the tutorial Create a JSON file in PHP. Screenshot of the file is shown below.

Please mouse over here to view the image.

Read an existing XML file and use the data to generate a JSON file with PHP.

//read the XML file
$xml = simplexml_load_file('members.xml');

//format the data
$x = array();
foreach($xml AS $member){
	$y = array();
	foreach($member AS $memberDetail){
		$y[] = (string)$memberDetail;
	}
	$x[] = $y;
}

//encode the formatted data
$json = json_encode(array('members'=>$x));

//generate the JSON file
header('Content-Type: application/json'); 
echo $json;

//result
/*
{"members":[["Jackson","Barbara","27","F","Florida"],["Kimball","Andrew","25","M","Texas"],["Baker","John","28","M","Arkansas"],["Gamble","Edward","29","M","Virginia"],["Anderson","Kimberly","23","F","Tennessee"],["Houston","Franchine","25","F","Idaho"],["Franklin","Howard","24","M","California"],["Chen","Dan","26","M","Washington"],["Daniel","Carolyn","27","F","North Carolina"],["Englert","Grant","25","M","Delaware"]]}
*/