是否存在关于json_decode在有效 JSON 字符串上返回 NULL 的 PHP 5.3 错误


Is there a PHP 5.3 bug concerning json_decode returning NULL on valid JSON strings?

我为朋友的wordpress网站编写了一个API,它依靠JSON API插件来获取她最近帖子的JSON提要。 它完美地工作了几个月,但几天前,当她的共享主机切换到 PHP 5.3 时,它完全停止工作(当然,他们没有提醒他们的用户 - 他们为什么要这样做?

我四处挖掘,在代码中发现一个奇怪的错误,它采用 JSON 字符串,并将解码的 JSON 对象返回给另一个函数。以前,代码(我发誓有效!)的工作方式如下:

    $json_string = file_get_contents($url_to_json_string);
    return json_decode($json_string);

这开始返回 NULL,json_last_error为 4(语法错误)。 我检查了utf8_encoding:很好。 我检查了BOM的奇怪性(根据这篇文章):很好。 我在 jsonlint.com 和 json.parser.online.fr 中验证了 JSON 字符串,它是完全有效的。 没有杂散的 html实体,没有徘徊的斜杠。 JSON 字符串本身很好,应该已经过验证。

然后,我将代码更改为:

    $json_string = file_get_contents($url_to_json_string);
    $json_object = json_decode($json_string);
    return $json_object;

它奏效了。

有谁知道为什么会这样?

不可打印的字符必须为 JSON 字符串。在下面使用:

json_decode( preg_replace('/['x00-'x1F'x80-'xFF]/', '', $json_string);, true );

这些链接可能适用:

  • json_decode() 返回空问题

  • https://github.com/sebastianbergmann/phpunit/issues/142

  • https://bugs.php.net/bug.php?id=45791

附注:

我刚刚通过几个验证器运行了您的代码片段:我没有看到任何错误......但你可能会:

  • http://www.functions-online.com/json_decode.html

  • http://jsonlint.com/

jsonDecode 中存在一般错误,其中"id":"google:1111111111111111111111111111111111111"被翻译成"id:"google:"11111111111111111111111111",这会导致语法错误。

要修复它,该行必须是:$json_without_bigints = preg_replace('/:''s*(-?''d{'.$max_int_length.',})/', ': "$1"', $input);

(它必须是:在前面的正则表达式中)。