Converting XML to JSON is a common task when working with web APIs and other data formats. JSON has become the preferred format for many developers, as it’s easy to read, write, and process. In this blog post, we will explore how you can convert XML to JSON in PHP.
Step 1: Load the XML File
First of all, you need to load the XML file that you want to convert to JSON. You can use simplexml_load_file() or simplexml_load_string() functions to load the XML file or string, respectively. In this example, we will use simplexml_load_file() to load an XML file called “example.xml”:
$xml = simplexml_load_file("example.xml");
Step 2: Convert the XML Object to JSON
After loading the XML file, you can use the json_encode() function to convert the XML object to a JSON string. The json_encode() function takes an array, so you need to cast the SimpleXMLElement object to an array to encode it:
$json = json_encode((array) $xml);
If you want to format the JSON string for better readability, you can use the JSON_PRETTY_PRINT constant as the second parameter of the json_encode() function:
$json = json_encode((array) $xml, JSON_PRETTY_PRINT);
Step 3: Save the JSON String to a File (Optional)
If you want to save the JSON string to a file, you can use the file_put_contents() function. In this example, we will save the JSON string to a file called “output.json”:
file_put_contents("output.json", $json);
Complete Example: Convert XML to JSON in PHP
Here’s the complete example that demonstrates how to convert an XML file to JSON:
Conclusion
In this blog post, we have learned how to convert XML to JSON in PHP using the simplexml_load_file(), json_encode(), and file_put_contents() functions. This technique can be helpful when working with web APIs and other data formats that require conversion between XML and JSON. Now you can easily convert XML data to JSON in your PHP projects!