Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress data in php and uncompress in javascript [closed]

Greerings all

Is there a way to compress data sent from php (server) and then uncompress the data using javascript (client)?

Thanking you

like image 217
Imran Omar Bukhsh Avatar asked Jul 03 '11 08:07

Imran Omar Bukhsh


3 Answers

I have to agree with @Domenic's answer here. @Nishchay Sharma is way off.

The only thing I'll add is if you want to do this on a per-script basis rather than configuring your entire server to compress everything, it's trivial to accomplish your goal by using PHP's gzencode() function coupled with a header call:

http://www.php.net/manual/en/function.gzencode.php

For instance, let's say you are retrieving a huge set of data via an Ajax call to a PHP page. You could configure the PHP page to use gzencode as follows:

<?php
$someBigString = gzencode('blahblah...blah');

header("Content-type: text/javascript");
header('Content-Encoding: gzip'); 

echo $someBigString;  
?>

(This is overly simplified, of course, but I'm keeping it simple.)

Your JS Ajax call will pull the data down, see the gzip header, and decompress it automagically. I personally use this technique for very large geo-coordinate data sets for Google Maps that can be many megabytes in size when uncompressed. It couldn't be easier!

like image 60
sstringer Avatar answered Sep 27 '22 18:09

sstringer


Yes; if you configure your server to serve up the data, which hopefully you are sending in a sane format like JSON, using GZIP compression, then you can just do an Ajax call in JavaScript and it will be automatically decompressed by the browser.

To set this up, copy these lines into your .htaccess file. (I assume you're using Apache, since that is the most common platform for serving PHP.)

like image 24
Domenic Avatar answered Sep 27 '22 18:09

Domenic


If keeping your response overhead small as possible is your goal then JSON DB: a compressed JSON format might also be of interest to you.

like image 44
Jay Sidri Avatar answered Sep 27 '22 18:09

Jay Sidri