【问题标题】:Php: How to echo json_encode as soon as it gets generatedPhp:如何在生成后立即回显 json_encode
【发布时间】:2014-09-24 21:36:48
【问题描述】:

对于一个rest API,我需要序列化大而深嵌套的json对象;

有没有办法在生成 json 时回显它?

如果我 echo json_encode($var) ,它将生成整个 json 并 然后 将其吐出:它会消耗内存,我必须等待整个生成完成,然后才能开始在我的浏览器中查看一些响应。

有没有办法强制 json_decode 有这种行为?

或者有没有图书馆可以做这种事情?

【问题讨论】:

  • 没有。除非您想推出自己的编码器。任何合理复杂程度的 JSON 编码数据结构都将是一大堆嵌套的 [ ... ]{ .... } 对。随时随地输出是可能的,但您很可能在另一端得到部分/损坏的字符串,特别是如果编码过程导致 OOM 条件或其他情况。

标签: php performance serialization json


【解决方案1】:

您唯一的选择是遍历您正在编码的对象并逐项对其进行编码,可能会编写您自己的 json 表示法来包含生成的 json。

例如

echo "["; // or { for an associative array (don't forget to output the json_encode()d keys and their colons)
$first = true;
for ($i = 0; $i < 10000000; $i++) {
    // json does not support trailing commas like php does
    // and you can't do an implode(",", $array) here because of the memory usage
    if ($first) {
        $first = false;
    } else {
        echo ",";
    }
    echo json_encode($i);
}
echo "]"; // or }

取自这里: http://forums.phpfreaks.com/topic/288266-json-encode-exceeds-allowed-memory/

【讨论】:

    【解决方案2】:

    您可以使用 smarty 模板将 json 文件从磁盘中读取。 或者你可以查看这个https://stackoverflow.com/a/4820537/3900160

    【讨论】:

    • 您可以通过给出一个关于如何使用“智能模板”在编码时回显 JSON 的明确示例来改进此答案。
    • 您确定 smarty 模板是动态生成的,并且在推送到 http 之前没有存储在内存中吗?
    猜你喜欢
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多