简体   繁体   中英

json gzip compression with php

I use this way to send serve a json file from my server.

$data = file_get_contents('cache/file.json');

ob_start('ob_gzhandler');

// Output as normal
echo ($data);

cache/file.json is not gzip compressed (plain json, without spaces the whole file is one long row).

I'm thinking Instead of gzipping the file everytime it is requested. Should I store it as a gzipped file

$gzjson = gzencode($data, 9);
file_put_contents('gzcache/file.json', $gzjson);

So I will minimize the server load? The idea is to gzip it and everytime the file is requested just serve the already gzipped file and not gzip it every time it's requested.

Does anyone think this is a good idea?

As your php sands some CPU load to generate zip so it mean - Yes it is good idea to have it cached and just read it instead if you have enough space on server.

Additionally you can implement old cached files remove logic. Check if file creation time( with http://php.net/manual/en/function.filemtime.php )

$creationTime = filemtime($zip);

if(time() - $creationTime >= 60 * 60 * 24 * 2) // 2 days
   @unlink( $zip );
}
// create new zip 

and if it older then some range(2 days) delete it and regenerate it again, so it mean you will regenerate that file once per range

I would let httpd to serve the json as a static resource. The server should take care about content negotiation and return archived file, if client can unpack it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM