후니의 블로그

PHP: Simple compression of JSON data 본문

웹프로그래밍/PHP

PHP: Simple compression of JSON data

Huzy Huzy 2016.06.16 09:36

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! 😆

0 Comments
댓글쓰기 폼