Easy JSON Encoding/Decoding in PHP

Update(2009-09-19): JSON encoding and decoding is built into PHP since PHP 5.20. You don't need Zend's JSON support if your PHP version is >= 5.20. Please see:

http://us2.php.net/manual/en/function.json-encode.php



http://us2.php.net/manual/en/function.json-encode.php

So you are writing a piece of PHP code to handle some Ajax request and you've just finished coding the business logic. It is time to output some server response so that the page which initiated the Ajax request can obtain the requested result.

You decided to use JSON because you don't want to get your hands dirty by traversing nodes after nodes. After encoding a fairly complex and nested PHP array into JSON, you find out writing such code is very unpleasant and you start wondering if there is an easier way to do this. The answer is yes - Zend Framework will save your day.

The rest of this article will show you how to use Zend Framework's Zend_Json component to encode and decode JSON formatted string in PHP.

Getting Zend Framework

You can get a copy of Zend Framework from Zend's official site.

Please note that Zend Framework requires PHP 5.1.4 or later. The code will not work if your PHP version is earlier than 5.1.4.

Copy Zend_Json to Your Project

Zend Framework is written with pluggable component in mind that most of its components can be selected for independent use. That means you don't have to copy the whole framework to your project directory. Indeed, for JSON encoding and decoding, you only need the following files from Zend Framework:

Copy above files to your project directory and keep the directory structure.

If you are confused about the directory structure or location of each files, you can download and see a sample project here.

Encoding PHP Data Structure

With Zend_Json, encoding PHP data structure into JSON formatted string is really easy. All you have to do is include Zend_Json to your PHP script and call Zend_Json::encode() with the variable you want to encode as parameter:

Running above script will produce a JSON representation of $result:

Reverse Operation: Decoding

Besides encoding, Zend_Json can also decode JSON formatted string. Provided a JSON formatted string, Zend_Json:decode() will transform it into native PHP array:

Above code will produce the following output:

As you can see, the result returned by Zend_Json::decode() in this example is an array and it holds the same data as the one in previous example.

Troubleshooting

Q: Why am I receiving the following error?

A: Your PHP version is too low. Make sure you are using PHP 5.1.4 or later.

Files

JSON encoding/decoding sample

Related Reading

Official Reference Guide

16 Comments Easy JSON Encoding/Decoding in PHP

  1. Jason

    here's my jquery script : // I should get an alert object if it works?
    but in firebug all I get is invalid label.

    var url = "http://127.0.0.1/projects/client_api/test?callback=?";
    $.getJSON(url,
    function(data){
    alert(data);
    });

    heres the json that I'm getting using zend_json:

    job_Description

    and here's the php in case it helps

    $json = new Zend_Json();
    $job_data = array(
    'job_Description' => 'My Job' ,
    'job_Notes' => 'My jobs notes are here.');

    echo $json->encode($job_data);

  2. Jason

    Unable to post json string ?

  3. Cuong

    The code has to be escaped through <pre></pre>.

    It seems like you haven't yet parsed this json string.

    With jQuery, try:

    for more information please visit
    http://thecodecentral.com/2007/11/20/the-missing-parameter-of-jquerypost.

    Without jQuery:

  4. Cuong

    Sorry your earlier comment was placed to moderation. I see what you are trying to do now.

    Apparently this is a JSONP request. You have to wrap your entire JSON response with the callback you specified in the URL, which is "callback" in this case:

    http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/

    If cross-site scripting is not required, you can simply change this line from

    to

  5. Mike

    So what does the Zend class do that the native PHP json_encode and json_decode functions don't? (Apart from being available in an earlier version of PHP)

  6. Pingback: YUI Based Lightbox - Revisited : Code Central

  7. Tracy

    I'm trying to decode a JSON string into a PHP array. The JSON string is stored in a PHP variable. How do I format this line: $result = Zend_Json::decode( 'wine');
    to use the variable containing the JSON string?

    Thanks!

  8. Web Design Bermuda

    I do not understand how this demonstrates an advantage. It is easy to JSON encode simple strings like above.

    Does Zend help with JSON encoding HTML or strings that need lots of escape characters.

    I am having a really tough time right now JSON encoding a string of HTML with a checkbox array. The checkbox array contains square brackets which throw off the JSON.

    How would Zend help me deal with this?

  9. Cuong

    The main advantage of JSON format to me, as a web developer, is the simplicity of exchanging data in Ajax based interaction. What I normally do is at the server side bundle all the data in a PHP array, encode the array in JSON format, and output it. At client side, decode the output by the PHP script into an JavaScript object.

    For more information see http://www.json.org/js.html.

    After the release PHP 5.2, I only use PHP build-in function
    json_encode for mostly all my JSON encoding needs. As far as I can recall, I have never used json_decode in PHP.

  10. Doug

    No one has mentioned that these are not core PHP functions. In order to get the JSON functions to work in PHP, you will have to install the JSON PECL PHP extension.

Comments are closed.