How to convert xml data into json using php?
In this article, we are going to see how to convert XML data into JSON format using PHP .
1. Code:
<?php // student details xml data taken as an String $xml = '<?xml version="1.0" encoding="utf-8"?> <student> <details> <address> <firstname>Soltuts 1</firstname> <city>kakumanu</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>Soltuts 2</firstname> <city>guntur</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>Soltuts 3</firstname> <city>ponnur</city> <zip>456345</zip> </address> </details> <details> <address> <firstname>Soltuts 4</firstname> <city>noida</city> <zip>456644</zip> </address> </details> </student>'; $xmldata = simplexml_load_string($xml); $jsondata = json_encode($xmldata); print_r($jsondata); ?>
2. Example:
Input:
$xml = '<?xml version="1.0" encoding="utf-8"?> <student> <details> <address> <firstname>Soltuts 1</firstname> <city>kakumanu</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>Soltuts 2</firstname> <city>guntur</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>Soltuts 3</firstname> <city>ponnur</city> <zip>456345</zip> </address> </details> <details> <address> <firstname>Soltuts 4</firstname> <city>noida</city> <zip>456644</zip> </address> </details> </student>';
Output:
{ "details": [ { "address": { "firstname": "Soltuts 1", "city": "kakumanu", "zip": "522112" }}, { "address": { "firstname": "Soltuts 2", "city": "guntur", "zip": "522112" }}, { "address": { "firstname": "Soltuts 3", "city": "ponnur", "zip": "456345" }}, { "address": { "firstname": "Soltuts 4", "city": "noida", "zip": "456644" }} ] }