Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^274) CHAPTER 18 ■ AJAX AND JSON
■Note If you wish to learn more about the JSON encoding itself, see the excellent online manual at
http://www.json.org.
Unfortunately, one of the biggest issues when working with JSON in PHP is that JavaScript
and PHP do not have directly compatible data types. JavaScript contains two collection types:
objects that are key/value pair collections and are analogous to an associative array in PHP,
and arrays that are strictly lists and are analogous to a numerically indexed array in PHP.
Any JSON implementation must include at least two methods: one to serialize a parameter
into a JSON-encoded string, and another to undo this operation and return a JSON string to a
variable. You can think of JSON encoding as a type of serialization.
The following sections introduce two alternative ways of using JSON with PHP:



  • The JSON PECL extension


•The Zend Framework

Json.org publishes the JSON parser script (json.js). You should download this now from
http://www.json.org/json.js, as most JSON applications require it to operate.

■Tip JavaScript minification can significantly reduce the size of the json.js library. See http://
http://www.json.org.

The JSON Extension.


The JSON PECL extension is enabled by default and ships with PHP 5.2 and later. This extension
provides the serialization functions required to convert PHP data types into JSON data:

string json_encode(mixed $value): This method encodes any variable type except a
resource and produces a JSON-encoded string representation of the data.

mixed json_decode(string $json, bool $associative): This method decodes a JSON-
encoded value into a PHP value. JSON cannot represent an associative array as anything
other than an object, and thus the bool $associative parameter can be used to cast the
object back into an associative array. This function is not an exact reversal of json_encode
and will decode only an array or object. To decode a simple value, it should first be encoded
wrapped in an array. If you try to decode a value that does not contain an array or an object,
you will see a return value of null.

■Tip You can convert an already encoded JSON basic data type to an array by padding the string with
square brackets: $var = '['. $var .']';.

McArthur_819-9.book Page 274 Friday, February 29, 2008 8:03 AM

Free download pdf