服务器端 PHP 压缩文件,客户端JS解压缩
程序员文章站
2024-03-13 23:53:28
...
有这样一个业务情景,客户端页面有个请求,PHP服务端返回的json文本数据比较大,一般都是好几MB。为了节省服务器流量以及节约带宽,要在后端将json文本数据压缩后传输到前端,前端Javascript对其进行解压后处理。
先后尝试了好几种方法,但是效果都不太好。现在主要分享以下两种能实现的方式。
方式一:
PHP后端用lz-string-php库压缩,该库有不同的版本可供选择。前端用相应的lz-string库实现解压缩。
该方式可以实现后端压缩前端也能解压,但是后端压缩很耗时,速度非常慢,故此不考虑该方式。
方式二:PHP后端用内置的zlib库的gzcompress()或gzencode()函数压缩,前端用pako.js解压缩。
后端PHP代码如下:
$map_json = '{"ed":"20170121 09:44:01","fs":[{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"003","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"005","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"004","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"007","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"008","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"026","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"033","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"034","oids":["0"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"035","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"037","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"038","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"041","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"042","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"047","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"046","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"048","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"051","oids":["1"]},{"usg":[1,1,1,1,1,1,1],"act":0,"fid":"053","oids":["4"]}],"qty":1,"sd":"20161021 09:44:01","cd":"72016102116762039687"}';
$map_json = gzcompress($map_json);
$map_json = base64_encode($map_json);
$data['mp'] = $map_json;
$this->assign('data', $data['mp']);
return $this->view->fetch();die;
前端JS代码如下:
<script type="text/javascript" src="/static/js/pako.js"></script>
<script>
var b64Data = '{$data}';
var strData = atob(b64Data);
var data = pako.inflate(strData);
console.log(data);
</script>
前端效果如下:
上一篇: 压缩解压和tar命令
下一篇: 使用go读取gzip格式的压缩包