Basic Usage

Usage of zend-json involves using two public static methods: Zend\Json\Json::encode() and Zend\Json\Json::decode().

// Decode a JSON value to PHP:
$phpNative = Zend\Json\Json::decode($encodedValue);

// Encode a PHP value to JSON:
$json = Zend\Json\Json::encode($phpNative);


By default, the above two calls will proxy to the json_decode() and json_encode() functions of ext/json, which is bundled in default installations of PHP. Using zend-json, however, ensures that the functionality works regardless of whether or not the extension is available. Additionally, the component provides some features not found in ext/json, such as encoding native JSON expressions, communicating class inheritance, and customizations around pretty printing.

Pretty-printing JSON

Sometimes, it may be hard to explore JSON data generated by Zend\Json\Json::encode(), since it has no spacing or indentation. In order to make it easier, Zend\Json\Json allows you to pretty-print JSON data in the human-readable format with Zend\Json\Json::prettyPrint().

// Encode it to return to the client:
$json = Zend\Json\Json::encode($phpNative);
if ($debug) {
    echo Zend\Json\Json::prettyPrint($json, array('indent' => ' '));

The second, optional, argument to Zend\Json\Json::prettyPrint() is an option array. Option indent allows providing an indentation string; by default, it uses four spaces.