This article mainly introduces how to use gzip to compress and output JSON data returned by PHP. the sample environment in this article is Linux and Apache server. if you need it, refer
1. Comparison between HTTP output with and without compression
2. enable gzip
Use apache mod_deflate module to enable gzip
Enabling method:
sudo a2enmod deflatesudo /etc/init.d/apache2 restart
Close method:
sudo a2dismod deflatesudo /etc/init.d/apache2 restart
3. set the type of gzip compression Output
The json output type is application/json.
In httpd. conf Join
AddOutputFilterByType DEFLATE application/json
<?php$data = array( array('name'=>'one','value'=>1), array('name'=>'two','value'=>2), array('name'=>'three','value'=>3), array('name'=>'four','value'=>4), array('name'=>'five','value'=>5), array('name'=>'six','value'=>6), array('name'=>'seven','value'=>7), array('name'=>'eight','value'=>8), array('name'=>'nine','value'=>9), array('name'=>'ten','value'=>10),);header('content-type:application/json');echo json_encode($data);?>
Set the output before gzip:
Output after setting gzip:
4. use gzip to compress the output of a single json file
After AddOutputFilterByType DEFLATE application/json is set, gzip is used to compress all data output in json format.
If you only want to use gzip to compress the output of a json file, you can use ob_start.
First, you do not need to set AddOutputFilterByType, and then add ob_start ('OB _ gzhandler') at the beginning of the code ');
<?phpob_start('ob_gzhandler');$data = array( array('name'=>'one','value'=>1), array('name'=>'two','value'=>2), array('name'=>'three','value'=>3), array('name'=>'four','value'=>4), array('name'=>'five','value'=>5), array('name'=>'six','value'=>6), array('name'=>'seven','value'=>7), array('name'=>'eight','value'=>8), array('name'=>'nine','value'=>9), array('name'=>'ten','value'=>10),);header('content-type:application/json');echo json_encode($data);?>