PHP JSON编码大数组时被截断

3
我遇到了一个使用json_encode显示JSON的问题。问题是在某个点之后它被截断了,我猜测在2500行左右。我读了很多stackoverflow和其他网站上的q&a,建议增加内存限制。我已经将其增加到32m,但它仍然被截断,而且我认为这不是问题,因为我已经输出了内存使用情况,并且使用true时我得到3.5mb,使用false时我得到1.5mb。我还尝试过将其编码为1000,但直到某个点它仍然会被截断。
我的JSON看起来像这样:
{"Id":"1"},{"Words":""},{"Position":"0"},{"Length":"0"},{"Pdf_Id":"1"}
再有2000行。
我的代码大致如下:
JSON文件
echo json_encode(array_values($db->getallqueryjsoncountStart("words_table","Allwords",4000,0)));


public function getallqueryjsoncountStart($table,$jsonparentname,$count,$start)
{

    $this->sqlquery = "select * from $table LIMIT $start,$count";
    $this->stmt = $this->conn->query($this->sqlquery);
    for ($i = 0; $i < $this->stmt->columnCount(); $i++) {
        $col = $this->stmt->getColumnMeta($i);
        $columns[] = $col['name'];
    }
    $this->initcnt = 0;
    $getqueryJson = array();

    while($this->row = $this->stmt->fetch()) 
    {
                for($x = 0;$x < sizeof($columns);$x++)
                {
                    $getqueryJson[][$columns[$x]] = $this->row[$columns[$x]];
                }
    }
    return $getqueryJson;
}

1
也许值得改变SQL查询中记录的顺序,以确保json_encode仍然在2500行后中断,而不是由于要编码的数据出现问题。 - M. Page
json_last_error() 的输出是什么?http://php.net/manual/en/function.json-last-error.php - robbmj
更改了顺序,仍在大约2500行处中断。json_last_error()返回0。感谢回复。 - Andre malupet
1个回答

4
如果“Words”列实际包含一些文本,则该值可能包含某些非法字符。请在json_encode函数中添加以下选项:
JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP

关于每个功能的描述,请参考手册页面

此外,看起来您构造$getqueryJson数组的方式不正确。请尝试进行以下更改

$getqueryJson = array();
while($this->row = $this->stmt->fetch()) 
{
    $row = array()
    for($x = 0;$x < count($columns);$x++)
    {
        $row[$columns[$x]] = $this->row[$columns[$x]];
    }
    $getqueryJson[] = $row;
}
return $getqueryJson; 

这样调用方法。

$table_data = $db->getallqueryjsoncountStart("words_table","Allwords",4000,0);
echo json_encode($table_data, 
                 JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

这将生成一个以下格式的JSON字符串。
[{"Id":"1", "words":"", "Position":"0","Length":"0","Pdf_Id":"1"},
 {"Id":"2", "words":"", "Position":"0","Length":"0","Pdf_Id":"2"},
 {"Id":"3", "words":"", "Position":"0","Length":"0","Pdf_Id":"3"},
 ...
 {"Id":"4000", "words":"", "Position":"0","Length":"0","Pdf_Id":"4000"}]

如果问题仍然存在,请尝试在调用json_encode之后立即调用json_last_error()

老兄,这太棒了!我不知道非法字符会导致JSON字符串截断。两者都可以正常工作,现在即使有超过10,000条记录,我也没有问题了。案子结束了,非常感谢。 - Andre malupet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接