Home > Article > Backend Development > Detailed explanation of how PHP compresses the returned JSON data and outputs it with gzip
How does PHP compress and output the returned JSON data with gzip? This article mainly introduces the method of using gzip compression to output the JSON format data returned in PHP. The example environment in the article is the Linux system and Apache server. Friends in need can refer to it. I hope to be helpful.
1. Comparison of HTTP output with compression and without compression
2. Turn on gzip
Use apache mod_deflate module to enable gzip
Open method:
sudo a2enmod deflate sudo /etc/init.d/apache2 restart
Close method:
sudo a2dismod deflate sudo /etc/init.d/apache2 restart
3. Set the type that requires gzip compression output
The output type of json is application/json, so you can set it like this
Add
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE application/json </IfModule>
<?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); ?>
before setting gzip in 7b799fe73e35dcfdc019b13f54de80e5bb15ed4aadeed04b3991578461de0768 in httpd.conf Output:
After setting gzip, output:
4. Single json Use gzip compressed output
After setting AddOutputFilterByType DEFLATE application/json, all data output in json format will be output using gzip compression.
If you only want to use gzip compression for a certain json and do not need the others, you can use the ob_start(); method to achieve this.
There is no need to set AddOutputFilterByType first, and then add ob_start('ob_gzhandler');
<?php ob_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); ?>
Related recommendations:
PHP array traversal foreach syntax structure and examples
PHP array sorting method summary
A brief analysis of json transmission in php and js
The above is the detailed content of Detailed explanation of how PHP compresses the returned JSON data and outputs it with gzip. For more information, please follow other related articles on the PHP Chinese website!