Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json_encode() not working in PHP 5.1? [duplicate]

Tags:

php

Possible Duplicate:
How can I decode json in PHP 5.1?

I am using json_encode function it works fine in my localhost...when i moved to server it not working ...I googled and find out that its does not support 5.1 version ...I want to use this function .any other possibility?wheather i need to upgrade to 5.2 or wat?

like image 759
shanmugavel Avatar asked Jul 27 '12 08:07

shanmugavel


3 Answers

Here's what I've used successfully for php 5.1 (Taken from comments under http://www.php.net/json_encode):

/**
 * Supplementary json_encode in case php version is < 5.2 (taken from http://gr.php.net/json_encode)
 */
if (!function_exists('json_encode'))
{
    function json_encode($a=false)
    {
        if (is_null($a)) return 'null';
        if ($a === false) return 'false';
        if ($a === true) return 'true';
        if (is_scalar($a))
        {
            if (is_float($a))
            {
                // Always use "." for floats.
                return floatval(str_replace(",", ".", strval($a)));
            }

            if (is_string($a))
            {
                static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
                return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
            }
            else
            return $a;
        }
        $isList = true;
        for ($i = 0, reset($a); $i < count($a); $i++, next($a))
        {
            if (key($a) !== $i)
            {
                $isList = false;
                break;
            }
        }
        $result = array();
        if ($isList)
        {
            foreach ($a as $v) $result[] = json_encode($v);
            return '[' . join(',', $result) . ']';
        }
        else
        {
            foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
            return '{' . join(',', $result) . '}';
        }
    }
}
like image 180
periklis Avatar answered Oct 31 '22 06:10

periklis


Yes json_encode is available in PHP 5 >= 5.2.0, you must either upgrade (recomended) or find a library that implements the functionality.

like image 35
Mihai Stancu Avatar answered Oct 31 '22 06:10

Mihai Stancu


Take a look at http://de.php.net/json_encode in the comments. Some people provided a PHP-written function which does the same. Only the performance will (most likely) not be as good as the native one ;-).

like image 31
thedom Avatar answered Oct 31 '22 06:10

thedom