3

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:

<?php
  // create a new cURL resource
$ch = curl_init("http://api.stackoverflow.com/1.0/questions?pagesize=5");

  // 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
curl_close($ch);

  // 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) ));"]
NULL

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

What am I doing wrong?

Thanks!

3 Answers 3

3

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

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_ENCODING,'gzip');  // Needed by API
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

$data = curl_exec($ch);
2

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.

1
  • Yes, that is quite weird and somewhat misleading. Jul 31, 2010 at 1:53
0

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.

You must log in to answer this question.

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