user1947561 user1947561 - 5 months ago 12
PHP Question

Getting null as response from Stack Overflow API with PHP

I use this code for PHP to get Stack Overflow reputation.

$feed = json_decode(file_get_contents("!*MxOyD8qN0Yghnep", true), true);
$array = $feed['items'][0];
$rep = $array['reputation'];
echo $rep;

But I get
for feed. Also user account is Jon Skeet which is where I get the ID 22656. How can I fix this?


The problem is that the response is also gzipped.

My preferred fix would be to use curl, with CURLOPT_ENCODING option.

function curl($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_USERAGENT, 'cURL');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING , "gzip");//<< Solution

    $result = curl_exec($curl);

    return $result;

$feed = curl("!*MxOyD8qN0Yghnep");

$feed = json_decode($feed,true);
$rep = $feed['items'][0]['reputation'];
echo $rep;//531776

Though, you can use normal FGC, then inflate the response back into uncompressed.

$feed = file_get_contents('!*MxOyD8qN0Yghnep');
$feed = gzinflate(substr($feed, 10, -8));

$feed = json_decode($feed,true);
$rep = $feed['items'][0]['reputation'];
echo $rep;//531776