Home > Backend Development > PHP Tutorial > 将PHP程序中返回的JSON格式数据用gzip压缩输出的方法_PHP

将PHP程序中返回的JSON格式数据用gzip压缩输出的方法_PHP

WBOY
Release: 2016-05-28 11:47:48
Original
1074 people have browsed it

1.使用压缩与不使用压缩的HTTP输出比较

201633154618959.jpg (447×226)

2.开启gzip

利用apache mod_deflate module 开启gzip
开启方法:

sudo a2enmod deflate
sudo /etc/init.d/apache2 restart

Copy after login

关闭方法:

sudo a2dismod deflate
sudo /etc/init.d/apache2 restart

Copy after login

3.设置需要gzip压缩输出的类型

json的输出类型是application/json,所以可以这样设置
在httpd.conf的中加入

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE application/json
</IfModule>

Copy after login

<&#63;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);
&#63;>

Copy after login

设置gzip前输出:

201633154714151.jpg (346×83)

设置gzip后输出:

201633154732511.jpg (334×99)

4.单个json使用gzip压缩输出

设置AddOutputFilterByType DEFLATE application/json后,所有json格式的数据输出都将使用gzip压缩输出。
如果只想某一个json使用gzip压缩输出,其他不需要,可以使用ob_start();方法来实现。

首先不需要设置AddOutputFilterByType,然后在代码最开始位置加入ob_start('ob_gzhandler');

<&#63;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);
&#63;>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template