【发布时间】:2014-08-10 00:55:33
【问题描述】:
我遇到了一个问题,即输出到 HTTP 客户端的 JSON 字符串在关闭标记附近被截断。
一个例子,
一个。期待看到 - ... ... "last_update":"2014-06-10 20:46:38","garden_id":"1"}],"message":null}
b.实际上是 - ... ..."last_update":"2014-06-10 20:46:38","garden_id":"1"}],"message":nul
最后两个字符由于某种原因被截断!!!
我在 Chrome 上尝试了 Postman,在控制台上尝试了 curl,所有输出都相同。所以看起来不是浏览器特定的问题。我的应用程序中的 JSON 字符串来自关联数组上的 PHP json_encode。 PHP 代码使用在 Apache 上运行的 CodeIgniter 框架。我尝试在 http 输出之前将 json 字符串写入文件,文件内容是 100% 正确的。所以这不是 PHP 中的 json 编码问题。
PHP 非常简单。我已经从数据库查询中构建了下面的数组(即 $finaldata)
{
"success": true,
"data": [
{
"file_id": "1",
"title": "xxx",
"create_date": "2014-05-18 21:30:19",
"auditor": "1",
"status": "1",
"last_updater": null,
"last_update": "2014-06-10 20:43:14",
"garden_id": "1"
},
{
"file_id": "2",
"title": "yyy",
"create_date": "2014-05-18 21:30:19",
"auditor": "1",
"status": "1",
"last_updater": null,
"last_update": "2014-06-10 20:43:14",
"garden_id": "1"
}
],
"message": null
}
“数据”有一个子数组,它可能是一个长数组,取决于数据库记录。然后将变量 $finaldata 传递给具有以下一般逻辑的输出函数:
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->format->factory($finaldata)->{'to_'.$this->response->format}();
header('Content-Length: ' . strlen($output));
输出函数由来自https://github.com/philsturgeon/codeigniter-restserver 的 RESTful 库构建。在这种情况下,它等于
header('Content-Type: Application/json');
$output = json_encode($finaldata);
但我发现了一个有趣的事情,即只有当字符串长度超过 8K 时才会出现问题。当我在 HTTP 响应之前将一个随机字符串(如“ZZZ”)附加到 JSON 字符串时,问题就消失了。我不知道背后的原因。这不是一个正确的 hack,因为我无法证明 8K 是一个真正的阈值。
有没有人遇到过这样的问题?任何建议或 cmets 表示赞赏。
【问题讨论】:
标签: php json codeigniter