8.3. Server-Side JSON Tools

When Crockford first proposed JSON, he was the only one creating tools for encoding and decoding. As the popularity of JSON grew, others started to step up and create client- and server-side libraries to facilitate its use. Although it is beyond the scope of this book to discuss every one of these tools, it is useful to take a look at one and then develop a solution using it.

8.3.1. JSON-PHP

JSON-PHP is a PHP library for encoding and decoding JSON information. This utility, written by Michal Migurski, is available for free at http://mike.teczno.com/json.html. To use this library, simply include the JSON.php file and create an instance of the Services_JSON object:

<?php
    require_once("JSON.php");
    $oJSON = new Services_JSON();
?>

The first line includes the JSON.php file that contains the Services_JSON object definition. The second line simply instantiates the object and stores it in the variable $oJSON. Now, you're ready to start encoding and decoding JSON in your PHP page.

8.3.1.1. The encode() Method

To encode a PHP object into a JSON string, use the encode() method, which accepts a single argument: an object to encode, which can be an array or a full-fledged object. It doesn't matter how the object or array was created, by using a class definition or not; all objects can be encoded using this method. Consider the following class definition:

<?php class Person { var $age; var $hairColor; var $name; var $siblingNames; function Person($name, $age, $hairColor) ...

Get Professional Ajax, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.