XML is a great format for data exchange. But JSON is used more and more for data exchanging and configuration. In my opinion JSON is a great, because it is more lightweight than XML. More and more apis work with JSON today. Recently I had to convert XML To JSON. Nothing special, just a simple XML String. In this article I’ll show you how to do this with only a few lines of code.
So, for this example I’ll use a file with the filename file.xml, which contains the following XML in it:
<?xml version="1.0" encoding="utf-8"?> <customers> <customer> <address> <firstname>John</firstname> <lastname>Smith</lastname> <street>Somestreet</street> <city>Sometown</city> <zip>12345</zip> </address> </customer> <customer> <address> <firstname>Emma</firstname> <lastname>Brown</lastname> <street>Anotherstreet</street> <city>Anothertown</city> <zip>23456</zip> </address> </customer> </customers> |
This XML file is in the same directory as our .php file is.
Next we need a .php file. This file will open the XML file and interpret the files content into an object, using the simplexml_load_file()
function. Next, we encode this object to JSON by using the json_encode()
function and assign it to a variable named $json
.
<?php // If file exists if (file_exists('file.xml')) { // Load XML file into an object $xml = simplexml_load_file('file.xml'); /* Now translate it to an JSON string and assign the JSON string to $json */ $json = json_encode($xml); // Output JSON print_r($json); } else { exit('Unable to open XML File'); } ?> |
That’s it! Now we have the XML data stored as a JSON string in $json
. In this examle, the JSON string will be outputted with print_r($json)
.
If you don’t have a XML file, but get your XML data as a string, e.g. from a database query, there is a similar way to do this. Just use simplexml_load_string()
function instead of simplexml_load_file()
. This will look like this:
<?php // String $xmlString = '<?xml version="1.0" encoding="utf-8"?> <customers> <customer> <address> <firstname>John</firstname> <lastname>Smith</lastname> <street>Somestreet</street> <city>Sometown</city> <zip>12345</zip> </address> </customer> <customer> <address> <firstname>Emma</firstname> <lastname>Brown</lastname> <street>Anotherstreet</street> <city>Anothertown</city> <zip>23456</zip> </address> </customer> </customers>'; // Load XML string into an object $xml = simplexml_load_string($xmlString); /* Now translate it to an JSON string and assign the JSON string to $json */ $json = json_encode($xml); // Output JSON print_r($json); |
For more information see:
- https://www.php.net/manual/en/function.simplexml-load-file.php
- https://www.php.net/manual/en/function.simplexml-load-string.php
- https://www.php.net/manual/en/function.json-encode.php
Here is an online xml to json converter https://freetools.site/data-converters/xml-to-json
Convert XML to JSON online for free https://freetools.site/data-converters/xml-to-json