IBM developerWorks recently posted an showing how to Convert XML to JSON in PHP. There are a few things in this article that I wanted pick on mention.
The first one is the "Browser-side data processing" section. Let me repeat it one more time, JSON Does Not Require eval( ).
Next up, why limit yourself to just XML to JSON conversion? The next most obvious conversion is JSON to XML. And what about JSON with callbacks? Since all of this is being done in PHP there is another, perhaps less obvious, conversion that we can do: serialized PHP to XML and or JSON. There is no reason why we shouldn’t be able to convert between all three of these formats in any order we want.
Back in November I wrote a simple library to convert Multiple Output Formats For Web APIs. The OutputFormat class (http://josephscott.org/code/php/outputformat/outputformat.tgz) is a simple wrapper format data as a PHP array, serialized PHP, XML, JSON and JSON with callback. Here’s an example:
<?php require("./OutputFormat.php"); $php_array = array( "person" => array( "name" => "Joseph Scott", "age" => 33, "url" => "http://joseph.randomnetworks.com/" ) ); $of = new OutputFormat(); $json_array = $of->arrayToJSON($php_array); $json_callback_array = $of->arrayToJSON($php_array, "my_js_function"); $serial_array = $of->arrayToSerial($php_array); $xml_array = $of->arrayToXML($php_array); print_r($php_array); print("nn"); print($json_array . "nn"); print_r($of->jsonToArray($json_array)); print("nn"); print($json_callback_array . "nn"); // This conversion will fail because it has a JavaScript callback in it. print_r($of->jsonToArray($json_callback_array)); print("nn"); print($serial_array . "nn"); print_r($of->serialToArray($serial_array)); print("nn"); print($xml_array . "nn"); print_r($of->xmlToArray($xml_array)); print("nn"); ?>
The code above is from the example file in http://josephscott.org/code/php/outputformat/outputformat.tgz.
Perhaps developWorks plans on future articles that will expand on this subject. In the meantime feel free to use my OutputFormat class. As an added bonus it works in both PHP 4 and PHP 5.