Convert XML to JSON in PHP
In this short article, we’ll explain to you how to convert XML to JSON in PHP. We can easily use the JSON format instead of XML. So we prefer to use JSON format.
Let’s take an example where we will try to convert the following xml code as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | $xml = "<?xml version='1.0'?> <catalog> <book id='bk101'> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <price>44.95</price> </book> <book id='bk102'> <author>Ralls, Kim</author> <title>Midnight Rain</title> <price>5.95</price> </book> <book id='bk103'> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <price>5.95</price> </book> </catalog>"; // Convert the XML string into an object. $xmlObject = simplexml_load_string($xml); // Encode the object value into a JSON format. $jsonString = json_encode($xmlObject); print_r($jsonString); // Output: { "book":[ { "@attributes":{ "id":"bk101" }, "author":"Gambardella, Matthew", "title":"XML Developer's Guide", "price":"44.95" }, { "@attributes":{ "id":"bk102" }, "author":"Ralls, Kim", "title":"Midnight Rain", "price":"5.95" }, { "@attributes":{ "id":"bk103" }, "author":"Corets, Eva", "title":"Maeve Ascendant", "price":"5.95" } ] } |
We can get the PHP array by calling json_decode() function as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | $array = json_decode($jsonString,true); print_r($array); // Output: Array ( [book] => Array ( [0] => Array ( [@attributes] => Array ( [id] => bk101 ) [author] => Gambardella, Matthew [title] => XML Developer's Guide [price] => 44.95 ) [1] => Array ( [@attributes] => Array ( [id] => bk102 ) [author] => Ralls, Kim [title] => Midnight Rain [price] => 5.95 ) [2] => Array ( [@attributes] => Array ( [id] => bk103 ) [author] => Corets, Eva [title] => Maeve Ascendant [price] => 5.95 ) ) ) |
Using foreach loop we can iterate each element of the associative array.
1 2 3 4 5 6 7 8 | foreach($array['book'] as $book){ echo $book['@attributes']['id']. ' - ' . $book['title'], '<br>'; } // Output: bk101 - XML Developer's Guide bk102 - Midnight Rain bk103 - Maeve Ascendant |
That’s it for today.
Thank you for reading. Happy Coding..!!