Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This is a very basic question. I just want to display a test batch of JSON with PHP, but I think I don't have the correct formatting, since the data received looks garbled when outputed, and it causes a data error if I try to decode it.

I know the JSON data is gzipped, but even with decompressing, I get an error. Here is the code I've tried:

  // create a new cURL resource
$ch = curl_init("");

  // set options        
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  // grab URL
$json = curl_exec($ch);

  // close cURL resource, and free up system resources

  // Decode JSON
var_dump(json_decode( gzuncompress($json) ));      

The output is:

Warning: gzuncompress() [function.gzuncompress]:
data error [on this line ==> "var_dump(json_decode( gzuncompress($json) ));"]

(stuff in the square brackets is my translation of its, "error on line ...")

What am I doing wrong?


share|improve this question
up vote 3 down vote accepted

Here is the relevant section of code from stack.PHP.

$ch = curl_init();

curl_setopt($ch,CURLOPT_ENCODING,'gzip');  // Needed by API

$data = curl_exec($ch);
share|improve this answer

gzuncompress is for ZLIB not GZIP. The two algorithms are related, but not identical. gzuncompress isn't strictly guaranteed to decompress all ZLIB streams actually, its just guaranteed to decode the results of gzcompress. Which is honestly really weird.

The appropriate function is gzdecode.
If that's not available, http_inflate should also work.

share|improve this answer
Yes, that is quite weird and somewhat misleading. – Peter Ajtai Jul 31 '10 at 1:53

Not sure why gzuncompress didn't work. My version of PHP doesn't have gzdecode. But I did just find the following:

You can instruct curl to decompress the returned string for you (since curl 7.10) by adding the line:

curl_setopt($ch,CURLOPT_ENCODING, 1);

The curl_setopt PHP manual reference.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .