Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip a JSON object before sending in PHP

Tags:

json

php

zip

I'm interested in zipping the text output from a JSON object on a server before transporting it to my mobile device that has requested the object. A small test of the txt zipping will reduce its size by about 80%! This is great for mobile! :)

I don't really need to save the zip file i create on the server at all, just have it reside in memory, then echo it out. I can unzip it on the android side no problem.

Anyways, I've done a little manipulation but I haven't been able to come up with anything that works, here's what I have so far:

while($e=mysql_fetch_assoc($q))
   $output[]=$e;
$zip = new ZipArchive();
$zip->addFromString("test",(json_encode($output)));
echo $zip;

I know im probably doing something massively wrong, im not very familiar with php. My $q is a cursor containing lots of sql rows, and if I use print(json_encode($output)); instead of all the zip shenanigans it works fine to output the raw text.

I suppose it doesnt have to be zip compression, but any compression would be helpful if you could point me in a proper direction I can likely figure it out. Thanks!

like image 990
Eric Avatar asked Jun 25 '11 14:06

Eric


1 Answers

you can use ob_start with ob_gzhandler:

if(function_exists('ob_gzhandler')) ob_start('ob_gzhandler');
else ob_start();

echo json_encode($output);
ob_end_flush();
like image 171
knittl Avatar answered Oct 12 '22 20:10

knittl