How to use JSON in PHP 4 or PHP 5.1.x

PostMar 16th, 2009 | Comments (10)
Here's an easy forward-compatible way to use JSON (json_encode() and json_decode()) in versions of PHP earlier than 5.2.

Download the Services_JSON PEAR package

And then add the following to your custom functions:

if (!function_exists('json_decode')) {
    function json_decode($content, $assoc=false) {
        require_once 'classes/JSON.php';
        if ($assoc) {
            $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        }
        else {
            $json = new Services_JSON;
        }
        return $json->decode($content);
    }
}

if (!function_exists('json_encode')) {
    function json_encode($content) {
        require_once 'classes/JSON.php';
        $json = new Services_JSON;
        return $json->encode($content);
    }
}


That's it! Your code will continue to work, even when you eventually upgrade to PHP 5.2.

Comments

RezaAug 16, 2009
Thank you so much.
LuisMar 13, 2010
Thank you very much! This code saved my day.
JayJun 3, 2010
Easier than I thought it would be. Excellent stuff!!!
DarioJun 9, 2010
great post, you solved my problem, thank you
KevinJul 2, 2010
Man, you are a life-saver!!
Clain DsilvaOct 15, 2010
Great Info dude it saved a lot of my time
RyanzkizenNov 7, 2010
Great Scott! Your my savior! Thanks! :D
MarkJan 25, 2011
There is also a good php4 json encode / decode library (that is even php5 reverse compatible) on this site: http://techblog.willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/

<a href="http://techblog.willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/">http://techblog.willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/</a>
ChrisFeb 8, 2011
This function doesn't give back long memo/longtext-fields from a MySQL DB, is there a limt for items or a special format, how longtext must be formatted. Regular textfields varchar(255) are working fine.
CarloMar 21, 2011
I LOVE YOU!

Post a comment

Name
URL
Email
Comment