CHAPTER 18 ■ AJAX AND JSON^275
The usage of these functions is straightforward, as demonstrated in Listing 18-1.
Listing 18-1. JSON Encoding/Decoding
$original = array('key'=>'value', 'key2'=>'value2');
$json = json_encode($original);
$restored = json_decode($json, true);
print_r($original);
print "\n". $json ."\n\n";
print_r($restored);
Array
(
[key] => value
[key2] => value2
)
{"key":"value","key2":"value2"}
Array
(
[key] => value
[key2] => value2
)
JSON in the Zend Framework.
The Zend Framework provides a wrapper to the JSON extension, but also contains a fallback for
systems that do not have the JSON extension enabled (typically installations older than PHP 5.2).
The functionality for the Zend Framework JSON system is provided through the Zend_Json
class and the following methods:
string Zend_Json::encode(mixed $value): This method is an alias of json_encode and
provides the same functionality.
mixed Zend_Json::decode(string $json [, int $decodeType = Zend_Json::TYPE_ARRAY]):
Unlike the json_decode function, the default mechanism for Zend_Json is to try to turn an
object into an associative array. You can pass the constant Zend_Json::TYPE_OBJECT as the
$decodeType parameter to override this behavior and return an object instead of an asso-
ciative array.
See Listing 16-12 in Chapter 16 for an example of using Zend_Json.
McArthur_819-9.book Page 275 Friday, February 29, 2008 8:03 AM