5

可能重复:
如何在 PHP 5.1 中解码 json?

我正在使用 json_encode 函数,它在我的本地主机中运行良好......当我移动到服务器时它不工作......我用谷歌搜索并发现它不支持 5.1 版本......我想使用这个函数。任何其他可能性?我是否需要升级到 5.2 或 wat?

4

3 回答 3

16

这是我成功用于 php 5.1 的内容(取自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) . '}';
        }
    }
}
于 2012-07-27T08:50:04.617 回答
2

Yesjson_encode在 PHP 5 >= 5.2.0 中可用,您必须升级(推荐)或找到实现该功能的库。

于 2012-07-27T08:50:25.703 回答
2

看看评论中的http://de.php.net/json_encode。有些人提供了一个 PHP 编写的函数来做同样的事情。只有性能(很可能)不如原生性能好;-)。

于 2012-07-27T08:50:33.400 回答