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:

// 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.)


$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.

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.