【问题标题】:Json_encode() not working in PHP 5.1? [duplicate]Json_encode() 在 PHP 5.1 中不起作用? [复制]
【发布时间】:2012-07-25 22:24:22
【问题描述】:

可能重复:
How can I decode json in PHP 5.1?

我正在使用 json_encode 函数,它在我的 localhost 中运行良好......当我移动到服务器时它无法正常工作......我用谷歌搜索并发现它不支持 5.1 版本......我想使用这个函数。还有其他可能吗?我需要升级到 5.2 还是 wat?

【问题讨论】:

标签: php


【解决方案1】:

这是我成功用于 php 5.1 的内容(取自 http://www.php.net/json_encode 下的 cmets):

/**
 * 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) . '}';
        }
    }
}

【讨论】:

  • 它能完美地发挥作用吗...?
  • 嗯,我已经用了很多年了,而且多年来没有问题,但我不能确定 100%。升级到php 5.2+是首选方案
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2016-08-20
      • 2015-03-31
      • 2015-08-29
      • 2018-01-06
      • 2017-06-17
      • 1970-01-01
      • 2013-05-12
      • 2015-01-14
      相关资源
      最近更新 更多