This post show how to convert XML to JSON using PHP code.
json_encode() function converts valid XML to JSON
Following is example:
In this example, we have an empty data.json file and a data.xml with the following content
data.xml
<staff>
<employee>
<name id="1">Alice</name>
<dob>January 1, 2000</dob>
</employee>
<employee>
<name id="2">Bob</name>
<dob>December 31, 2000</dob>
</employee>
</staff>
The following code will read this XML file, generate JSON and output it to data.json file.
<?php
$myJSON = fopen("data.json", "w");
$myXML = simplexml_load_file("data.xml");
fwrite($myJSON, json_encode($myXML));
fclose($myJSON);
?>
Line 1: opens data.json file with “w” option meaning you can write content to it
Line 2: opens data.xml file and loads its data. Note the use of simple_load_file() function.
Line 3: converts XML to JSON and writes the JSON into data.json file. Note the use of json_encode() function to convert data.
Line 4: closes data.json file for writing
data.json
{
"staff": {
"employee": [
{
"name": {
"-id": "1",
"#text": "Alice"
},
"dob": "January 1, 2000"
},
{
"name": {
"-id": "2",
"#text": "Bob"
},
"dob": "December 31, 2000"
}
]
}
}