Using json_encode() and json_decode() in PHP4

I use json_encode() a lot for AJAX calls. Teamed with jQuery’s $.getJSON(), it’s too convenient not to use. Unfortunately, json_encode() doesn’t come standard until PHP 5.2. To add insult to injury, most current *nix distros don’t include PHP 5.2 in their official repositories yet.

And what about all of those die-hard PHP 4 users? (I know — there aren’t a lot of those out there — but there are a lot of folks that are still stuck running it on legacy systems for whatever reason)

I quickly got tired of passing back pipe-delimited strings and raw HTML to my JavaScript programs simply because the server I was working on couldn’t be upgraded to PHP 5.2, so I went searching for a “future-friendly” solution to my json_encode()/json_decode() dilemma. I wanted a solution that would enable me to use both of these functions as if my scripts were running under PHP 5.2 (and without recompiling PHP or installing a separate module).

What I ended up with was the code that was proposed (and ultimately accepted) for the “Services_JSON” PEAR package. The source code is about 800 lines and comes in the form of a PHP class. It’s not at all hard to use, but it still isn’t as convenient as json_encode() and json_decode().

To achieve the simplicity I desired, I added a few lines to the very bottom of the class file:

<?php
// Future-friendly json_encode
if( !function_exists('json_encode') ) {
    function json_encode($data) {
        $json = new Services_JSON();
        return( $json->encode($data) );
    }
}

// Future-friendly json_decode
if( !function_exists('json_decode') ) {
    function json_decode($data) {
        $json = new Services_JSON();
        return( $json->decode($data) );
    }
}
?>

Just include the class file and use json_encode() and json_decode() exactly as you would with PHP 5.2. (It is worth mentioning that your scripts will not “break” when your system gets upgraded to PHP 5.2. The code will simply become benign.)

<?php
include("JSON.php");

$a = json_encode( array('a'=>1, 'b'=>2, 'c'=>'I <3 JSON') );
echo $a;
// Outputs: {"a":1,"b":2,"c":"I <3 JSON"}

$b = json_decode( $a );
echo "$b->a, $b->b, $b->c";
// Outputs: 1, 2, I <3 JSON
?>

All you have to do is append the two functions above to the original source code, or download the modified version that I’ve provided for your convenience.

A very special thanks goes out to Michal Migurski for authoring this fantasic PHP class.

If you enjoyed this article, please share it with a friend!

24 Responses to Using json_encode() and json_decode() in PHP4

  1. andy says:

    awesome thanks! I wondered why my json_encode wasn’t working after I changed server, now I don’t have to worry.

    nice one

  2. Curt says:

    niccccccceee! THANKS!

  3. Florin Jurca says:

    Well nice job.
    But there is still a little problem of compatibility.
    json_decode must have a second parameter.
    A flag true/false for controlling output mode array/object.
    So I think the following patch should work for json_decode:

    if( !function_exists(‘json_decode’) )
    {
    function json_decode($data, $output_mode=false) {
    $param = $output_mode ? 16:null;
    $json = new Services_JSON($param);
    return( $json->decode($data) );
    }
    }

    Regards,
    F.J.

  4. Cory LaViska says:

    @Florin: The second parameter is optional and is only required when you want to convert returned objects into associative arrays. See http://www.php.net/json_decode for more details.

  5. Schmoo says:

    “It is worth mentioning that your scripts will not “break” when your system gets upgraded to PHP 5.2. The code will simply become benign.”

    At 800 lines included, parsed and then ignored I’d call it “benign-ish” ;)

    How about duplicating the function exists call to decide whether the include happens at all?

    if( !function_exists(‘json_decode’) ) { include(“JSON.php”); }

    (I’d probably leave the other check in there to be honest, just to idiot-proof it for the times I’m not paying enough attention…)

  6. Ather says:

    when i try to run a test file it gives me error:

    Fatal error: No parent class available in this context in JSON.php on line 786

    any reason why?… thanks

  7. Ather says:

    Sorry this is the file which i run gives me an error that i mentioned in last post.

    < ?php
    include("JSON.php");

    $a = json_encode( array('a'=>1, ‘b’=>2, ‘c’=>’I <3 JSON') );
    echo $a;
    // Outputs: {"a":1,"b":2,"c":"I <3 JSON"}

    $b = json_decode( $a );
    echo "$b->a, $b->b, $b->c”;
    // Outputs: 1, 2, I <3 JSON
    ?>

  8. Cory LaViska says:

    @Ather: not sure. What version of PHP are you running?

  9. This works great in PHP4, but when my ISP suddenly change to a JSON-Supported version, it suddenly stopped working. I had to back out to PHP4 to get it to work again… Any ideas what I should be looking for on that?

    Thanks!

  10. Cory LaViska says:

    @Daniel: if, for some reason, it’s causing problems and your new version of PHP supports JSON then just remove it. Hopefully that sorts out your problem.

  11. vic says:

    Good Idea. Thx very much, i must try it.

  12. Basse says:

    Hi!
    Thanks a lot for this, I’ll try it out right now.
    I’m working on a customers site, and I realized I had some problems when I checked which version of PHP their webserver was running. 4.x of course, and no support for json_encode() that I needed… -_-
    Thanks again!

  13. Matthias says:

    Many thanks, this class was very helpful for creating my girlfriends website. (The host-provider doesn’t supports Json, incredible!)

  14. ldurniat says:

    Your text help me very much. All day i was searching for solution(i use php4).i want to use ext js for project. Thx.

  15. Faheem says:

    Excellent job.. and very handy work…
    thank bro..

    Keep on going..

  16. sim says:

    Thank you – this helped me a lot – coding on a friday evening …..finished now!

  17. Tuyen Truong says:

    Thank you Cory and Florin. You two make my day seem easier

  18. I think I love you! THANKS!

  19. Wayne says:

    Great class, thank you so much :)

  20. Islam Ossama says:

    Honestly, I don’t know how to thank you enough for this solution! You’re a true life saver!

  21. Thanks a lot for all the help!!!!

  22. A well-written post. Ditto the positive comments above. Many thanks.