9

How can I read a response from Stackoverflow API in PHP? The response is GZIP-ed. I found e.g. the following suggestion:

$url = "http://api.stackoverflow.com/1.1/questions/" . $question_id;
$data = file_get_contents($url);
$data = http_inflate($data);

but the function http_inflate() is not available on the installation that I am using.

Are there some other easy ways to accomplish it?

Jiri Kriz
  • 9,192
  • 3
  • 29
  • 36

2 Answers2

23

A cool way http://www.php.net/manual/en/wrappers.compression.php

Notice the use of a stream wrapper, compress.zlib

$url = "compress.zlib://http://api.stackoverflow.com/1.1/questions/" . $question_id; 
echo $data = file_get_contents($url, false, stream_context_create(array('http'=>array('header'=>"Accept-Encoding: gzip\r\n"))));

or using curl

$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => $url
  , CURLOPT_HEADER => 0
  , CURLOPT_RETURNTRANSFER => 1
  , CURLOPT_ENCODING => 'gzip'
));
echo curl_exec($ch);

edited-- other methods removed because they don't send an Accept-Encoding http header.

goat
  • 31,486
  • 7
  • 73
  • 96
0

Use this to get gzip encoding json response its working like a charm

function get_gzip_json($url) {
 $ch = curl_init();
 curl_setopt_array($ch, array(
   CURLOPT_URL => $url,
   CURLOPT_HEADER => 0,
   CURLOPT_RETURNTRANSFER => 1,
   CURLOPT_ENCODING => 'gzip',
 ));

 $json = curl_exec($ch);
 $json= mb_convert_encoding($json, "UTF-8", "UTF-8"); 

 return $json;
}