PHP: Simple compression of JSON data

Published:

Just discovered how super simple it was to add some gz compression when for example providing JSON data from PHP.

All you need is regular output buffering with the ob_gzhandler as output callback.

// Fetch some data
$data = get_data();

// Turn on output buffering with the gzhandler
ob_start('ob_gzhandler');

// Output as normal
echo json_encode($data);

The cool thing is that it actually looks at what the browser accepts before doing anything.

Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages.

Tried adding it for a text field with timezone auto-completing for example, and without this handler:

Content-Length:    5517
Content-Type:      application/json

With this handler:

Content-Encoding:  gzip
Vary:              Accept-Encoding
Content-Length:    1775
Content-Type:      application/json

Do like! 😊