Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
Vilx- Avatar asked Jan 10 '10 14:01

Vilx-


People also ask

How to compress JSON data in PHP?

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.

Can you compress JSON?

As text data, JSON data compresses nicely. That's why gzip is our first option to reduce the JSON data size. Moreover, it can be automatically applied in HTTP, the common protocol for sending and receiving JSON. Let's take the JSON produced with the default Jackson options and compress it with gzip.

What is JSON format PHP?

JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.


2 Answers

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.

like image 144
Gumbo Avatar answered Sep 21 '22 22:09

Gumbo


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

\u00f3 -> Ĺ› = Ś

eq:

 json_encode($data,JSON_UNESCAPED_UNICODE);
like image 36
user956584 Avatar answered Sep 20 '22 22:09

user956584