php压缩json数据

发布时间 2023-11-21 21:36:25作者: carol2014

最近在优化一个页面:ajax请求异步数据,特定情况下,json数据达到100MB左右,仅数据传输时间就需要10-20s左右,简直太慢了。

检索资料看怎么压缩json数据

有效的方法:

ob_start('ob_gzhandler'); //压缩数据
header('Content-Type: application/json');

$data = [];
for ($i = 0; $i < 100000; $i++) {
    $data[] = ['name' => 'aa' . $i, 'age' => random_int(10, 99)];
}

echo json_encode($data);

 

  $.ajax({
    url: "http://localhost:3000/php-demos/test.php", 
    type: "get",
    dataType: "json",
    success: function (data) {
      console.log(data);
    },
    error: function (xhr, err) {
      console.log(xhr, err);
    },
  });

  

 

数据大小虽然变小了,然而时间却增多了

还是要看看有没有其它的方法

 

 踩过的坑: 

header('Content-Type: application/json');
header('Content-Encoding: gzip');

$data = [];
for ($i = 0; $i < 100000; $i++) {
    $data[] = ['name' => 'aa' . $i, 'age' => random_int(10, 90)];
}

$json = json_encode($data);
$comoressed = base64_encode(gzcompress($json, 9));
echo $json;

 

出现下面的错误

 错误原因应该是发送的数据不是gzip数据

上面压缩处理过的字符串也无法用pako.js解压缩