在PHP中编码数据并在Javascript(ajax)中解压缩

In order to reduce the size of my json file, I wanted to zip it. Hence, I am trying to compress json data file sent from php server :

header('Content-Encoding: gzip'); 
$output = gzencode(json_encode($data));     
echo $output;

And then, uncompress it in javascript (ajax methodd) :

$.ajax({
    url: url,
    type: "GET",
    headers : {'Accept-Encoding': 'gzip '},
    async: true,
    success: function (data) {
        console.log("sucess !!");
        console.log(data);
        ... 
    )};

I also modified apache server in order to uncompress it automagically :

LoadModule deflate_module modules/mod_deflate.so

And :

 <IfModule mod_headers.c>
  <FilesMatch ".(js|css|xml|gz|txt|json)$">
      Header append Vary: Accept-Encoding
  </FilesMatch>

However, I couldnt get the data properly (it stills compress).

Could you please let me know what I am doing wrong ?

Thank you

1个回答



要将gzip用于API,不需要在应用程序级别实现它(在PHP中压缩数据并在JS中解压缩)。 在这种情况下,数据应由Web服务器(Apache)压缩并由客户端(浏览器)解压缩。 此过程是透明的,独立于PHP或JS代码。</ p>

确保将Web服务器配置为对API端点使用压缩。 要测试它,请运行 curl -I -H'Accept-Encoding:gzip,deflate'https://your.domain/api/endpoint/name </ code>或检查浏览器devtools中的请求(在“网络”选项卡下) )。</ p>

如果响应中有 content-encoding:gzip </ code>标头,则表示服务器使用gzip进行压缩。</ p>
< / DIV>

展开原文

原文

To use gzip for the API there's no need to implement it on the application level (compress data in PHP and decompress it in JS). In this case the data should be compressed by the web server (Apache) and decompressed by the client (browser). This process is transparent and independent from the PHP or JS code.

Make sure that the web server is configured to use compression with your API endpoints. To test it run curl -I -H 'Accept-Encoding: gzip,deflate' https://your.domain/api/endpoint/name or inspect the request in your browser devtools (under Network tab).

If there's a content-encoding: gzip header in the response, it means that the server uses gzip for compression.

drn61317
drn61317 它完美地运作! 谢谢
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐