問題描述
在 PHP 中壓縮 JSON 字符串並在 Javascript 中解壓縮以進行 Google API 的數據庫查詢 (Compress JSON string in PHP and decompress in Javascript for Database query for Google API)
I generate a JSON files in my PHP code (by running a database query). This JSON file is downloaded on the client side in my Javascript using the Data Queries example of the Google Chart Tools:
function initialize() {
// Replace the data source URL on next line with your data source URL.
// Specify that we want to use the XmlHttpRequest object to make the query.
var opts = {sendMethod: 'xhr'};
var query = new google.visualization.Query('http://spreadsheets.google.com?key=123AB&...', opts);
// Optional request to return only column C and the sum of column B, grouped by C members.
query.setQuery('select C, sum(B) group by C');
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
The JSON files are rather large. What is the best way to compress the JSONstring in PHP and decompress it in Javascript?
參考解法
方法 1:
<p>@Gavin gave the right answer in a comment above:
His answer was: Look into GZIP'ing your content. If your server is setup correctly, it can compress any application/json content and then your browser "should" automatically decompress it. a href="http://bearpanther.com/2012/04/11/gzip-json-generated-on-the-fly" rel="nofollow"http://bearpanther.com/2012/04/11/gzip-json-generated-on-the-fly</a></p>
方法 2:
The question is "How to compress JSON with PHP". The answer is use ob_gzhandler
. Use this approach only, if you do not have access to the server configuration.
I suggest the following solution, where you don't have to write any PHP code and get gzip on all your json resources:
change your server configuration to allow automatical gzip'ing of negotiated content
Apache .htaccess
`AddOutputFilterByType DEFLATE text/html ... application/json`
Nginx server.conf
gzip on; // if not already set
gzip_comp_level 9;
gzip_types application/json;
Example with more gzip_types:
gzip_types text/text text/html text/plain text/xml
text/css application/x-javascript application/javascript
application/json;
(by Ruut、Ruut、Jens A. Koch)