Vilx-
Vilx-

Reputation: 106912

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 n2 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.

Upvotes: 21

Views: 43071

Answers (3)

userlond
userlond

Reputation: 3818

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>

Upvotes: 2

user956584
user956584

Reputation: 5559

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

\u00f3 -> Ĺ› = Ś

eq:

 json_encode($data,JSON_UNESCAPED_UNICODE);

Upvotes: 5

Gumbo
Gumbo

Reputation: 655229

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.

Upvotes: 55

Related Questions