|
I've noticed that many people still want to do things the hard way. People don't want to use libraries to help them out. They construct Json code by hand crafting curly braces, and quoting their values. In PHP it is so simple to do Json, that really you have no excuse not to. You have a couple of options, the PHP extension, which comes with most PHP installations nowadays, or another library, most importantly, my preferred one, Zend_Json, which is part of the Zend Framework. Both libraries have two functions, encode and decode. Encode takes in an object and spits out the string that represents the Json. Decode is the opposite, feed in Json, and the function spits out a generic PHP object of type stdClass, that represents exactly the Json, (including translating Json arrays to PHP arrays). Luckily, PHP and Javascript are dynamic languages, so you can add properties to any object, including changing the types and whatnot, you don't need to specify a 'Class' in order to construct a message. To construct some Json in PHP(using the PHP extension), here's an example: $obj = new StdClass(); $obj->mythings = array(1, 2, "3", false); $obj->person = new stdClass(); $obj->person->name = "Kekoa"; $obj->person->age = 88;
echo json_encode($obj); Which prints out: {"mythings":[1,2,"3",false],"person":{"name":"Kekoa","age":88}} Wow. Exciting, it even takes care of quoting strings, and not quoting numbers, and booleans. Also takes care of any internal arrays or objects. Decoding Json is easier: $jsonText = '{"mythings":[1,2,"3",false],"person":{"name":"Kekoa","age":88}}';
$obj = json_decode($jsonText); print_r($obj);
When executed, the print_r reveals the PHP structure of $obj (the boolean false doesn't get printed nicely, but it's there, I promise): stdClass Object ( [mythings] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => )
[person] => stdClass Object ( [name] => Kekoa [age] => 88 )
) Since objects and associative arrays in PHP are essentially the same thing, you can request to have the decoder return your decoded Json into an associative array. Simply set the 2nd parameter to json_decode() to true. This is what you'll get: Array ( [mythings] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => )
[person] => Array ( [name] => Kekoa [age] => 88 )
) FYI, Zend_Json works almost exactly, but uses the static functions Zend_Json::encode() and Zend_Json::decode() instead. The built in command is definitely faster(written in C) but the Zend_Json decoder is much more flexible(forgiving) if you're reading Json from someone who say, handcrafted their own Json instead of using a library. Check this outdated, but still interesting comparison of Json libraries: http://gggeek.altervista.org/sw/article_20070425.html Do you need to use the whole Zend Framework to use Zend_Json-- no, it's a component framework, you can pull out the Json utilities without any external coupling.
|