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

在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

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.