简体   繁体   中英

How to compress JSON with PHP?

I'm writing a little analysis page which will help me hunt down bugs in an application. In essence it allows to visually compare actual data and log entries, plus perform a bit of analysis on the data.

Since this is for debugging only and since I will be deploying this on the live site I want it to have as little server load as possible. Several of the analysis options will include rather heavy substring searching or n 2 operations, so I'm going to offload this to the client.

This means that the PHP page will just take the data from the tables and logs, JSON some of it, and write it out. The client Javascript will then do all the analysis etc.

The problem is that the JSON'ed data will be several MB large, and my connection to the server - slow. It would be nice to compress the data somehow. Anyone have ideas?

The environment is PHP + Apache; I don't know if mod_gzip will be installed; and I have no control over it.

You can compress the data with PHP's output control . Just put this call at the start of your script before any output:

ob_start('ob_gzhandler');

Now any output will be compressed with either gzip or deflate if accepted by the client.

In PHP 5.4 is now JSON_UNESCAPED_UNICODE so you can replace char:

\ó -> Ĺ› = Ś

eq:

 json_encode($data,JSON_UNESCAPED_UNICODE);

If apache is your choice (and it is, like mentioned in original question), you may add some rules into .htaccess:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html
    # Add any mime-type you think is appropriate here
    AddOutputFilterByType DEFLATE application/json
</IfModule>

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