【问题标题】:json_encode() returns null since array has huge number of recordsjson_encode() 返回 null 因为数组有大量记录
【发布时间】:2015-06-12 06:58:53
【问题描述】:

我使用json_encode($response) 列出了目录中的所有文件。由于$response的数组中有近8000条记录,所以在页面中显示时返回null

我对这个问题进行了研究。到目前为止,我找不到任何解决方案。

这是我的代码:

$response['content'] = Files::$output;
echo json_encode($response);
Files::$output` /* this will return the list of files in the html format. */

当我尝试echo json_last_error_msg(); 时,它返回:

格式错误的 UTF-8 字符,可能编码不正确

【问题讨论】:

  • 你是如何在页面上显示的,你能发布你的代码吗?
  • 你尝试过更改php.ini中的memory_limit参数吗?
  • 在我的 php.ini 中我设置了内存限制 128M
  • 您如何得出结论认为问题在于输入的 size 而不是其他问题?你检查过json_last_error_msg吗?
  • 所以你的问题原来是stackoverflow.com/questions/14868096/…的重复

标签: php arrays json


【解决方案1】:

当通过json_encode 编码时,JSON 只能接受有效的 UTF 字符。

很可能,您的输入格式错误(如您的错误消息所述),这很可能是 Windows 代码页的某种变体。

为确保您的数组没有无效的 JSON 数据,您可以在数据库层对其进行转换(假设您使用的是数据库),或者执行以下操作(假设您的格式错误latin1/ISO-8859-1作为您不良数据的原因):

foreach ($row as $key => &$value) {
    if ( ! mb_check_encoding($value, "UTF-8")) {
        // assume base is latin1; your mileage may vary
        $value = mb_convert_encoding($value, "UTF-8", "ISO-8859-1");
    }
}

您不能真正强制 json_encode 解析您的无效数据,因此您必须将您的数据集转换为有效的 UTF-8。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 2016-12-08
    • 2017-03-20
    • 2016-05-24
    • 2016-06-02
    • 2011-07-11
    相关资源
    最近更新 更多