XML 2 JSON Page

  tonyperson  >  Home  >  code  >  xml2json


Summary

In many companies we already have a xml system for delivering logic to the front end. This page will show you how to painlessly translate this ungainly XML into cleaner, smaller and javaScript friendly objects in codeigniter or any other object oriented MVC framework by using PHP. This way should relieve the client-side for any heavy javaScript to json conversion methds, although they are fine too!

IMPORTANT! I have just migrated this code to a new server with the latest PHP and this code is not working correctly. I am looking into it. Thanks for your patience. - Tony

BTW- while you are waiting for me to fix this, have a listen to Everybodys Got Something to Hide Except Me and My Monkey (Beatles Cover) on iComps. Hope you enjoy it!

XML

Here is a xml array this can be from either a dynamic/static text file or a result of a httpRequest from the server.

<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<contact id="1">
<name>John Doe</name>
<phone>123-456-7890</phone>
<address>
<street>123 ANYStreet</street>
<city>ANY Town</city>
<state>ANY State</state>
<zipCode>37075</zipCode>
</address>
</contact>
</contacts>

PHP Code

Here is the code I use to "Magically Transform" the xml array to a JSON String. Some of these variables are delcared beforehand. ex.EMPTY_STR

The reason you'll want the EMPTY_STR variable is that you'll want to accomodate null values and return them as a blank string or else you will get errors.

//make this xml array into JSON please.
function transfXml2Json($xmlStringContents) {
$sXMLobj = simplexml_load_string($xmlStringContents);

if ($sXMLobj == null) {
return(EMPTY_STR);
}

$jsonOutput = EMPTY_STR;

// Convert the XML structure into PHP array structure. Using above function.
$array1 = convSXEOArray($sXMLobj);

if (($array1 != null) && (sizeof($array1) > 0)) {
// Let us now convert it to JSON formatted data.
$jsonOutput = json_encode($array1);
} // End of if (($array1 != null) && (sizeof($array1) > 0))

return($jsonOutput);
} // End of function transformXmlStringToJson

Then the code I call to work the function in the Controller is:

$data['jsonOutput'] = transfXml2Json($xmlStringContents);

$this->load->view('xml2json', $data);

JavaScript

Here is the Javascript needed to interpret the JSON format.

//Javascript
var result = ;
jsonResponse = eval('(' + result + ')');

Output

Here is the XML output code.

John Doe 111-456-7890
123 ANYStreet ANY Town ANY State 37075


JSON

Here is the JSON output code.

Helpful Links

Check out the codeigniter article on JSON functionality -http://codeigniter.com/wiki/JSON_Helper

Check out the codeigniter article on XML_Helper functionality -http://codeigniter.com/wiki/XML_Helper

You may want to check out my other page on JSON - http://tonyperson.com/code/json