Compress data in php and uncompress in javascript [closed]

最后都变了- 提交于 2019-12-04 01:40:47

问题


Greerings all

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

Thanking you


回答1:


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!




回答2:


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.)




回答3:


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.



来源:https://stackoverflow.com/questions/6561828/compress-data-in-php-and-uncompress-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!