How to convert XML to JSON with PHP?

Spread the love

Sometimes, we want to convert XML to JSON with PHP.

In this article, we’ll look at how to convert XML to JSON with PHP.

How to convert XML to JSON with PHP?

To convert XML to JSON with PHP, we can use the simplexml_load_string, json_encode and json_decode functions.

For instance, we write

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json, true);

to call simplexml_load_string to load the $xml_string into the $xml object.

Then we call json_encode with $xml to convert $xml into a $json string.

Next, we call json_decode with $json and true to convert the $json into an $array.

Conclusion

To convert XML to JSON with PHP, we can use the simplexml_load_string, json_encode and json_decode functions.

Leave a Reply

Your email address will not be published.