1

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?

Ruut
  • 1,091
  • 1
  • 16
  • 29
  • 2
    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. http://www.bearpanther.com/2012/04/11/gzip-json-generated-on-the-fly/ – Gavin Aug 20 '12 at 07:49
  • duplicate http://stackoverflow.com/questions/2037349/how-to-compress-json-with-php – Peter Aug 20 '12 at 17:14

2 Answers2

0

@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. http://bearpanther.com/2012/04/11/gzip-json-generated-on-the-fly

Ruut
  • 1,091
  • 1
  • 16
  • 29
0

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;
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141