4

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

$feed = json_decode(file_get_contents("http://api.stackexchange.com/2.1/users/22656?order=desc&sort=reputation&site=stackoverflow&filter=!*MxOyD8qN0Yghnep", true), true);
$array = $feed['items'][0];
$rep = $array['reputation'];
echo $rep;

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

Smar
  • 8,109
  • 3
  • 36
  • 48
user1947561
  • 1,117
  • 2
  • 8
  • 13
  • isnt it better to put the content from that page in an array? instad of json – William N Feb 12 '13 at 04:21
  • @WilliamN that what i do.. json_decode make json into php array – user1947561 Feb 12 '13 at 04:22
  • i put http://api.stackexchange.com/2.1/users/22656?order=desc&sort=reputation&site=stackoverflow&filter=!*MxOyD8qN0Yghnep in jsonlint = invalid even though url... go to http://api.stackexchange.com/2.1/users/22656?order=desc&sort=reputation&site=stackoverflow&filter=!*MxOyD8qN0Yghnep in chrome copy json put in jsonlint = valid json... i no understnad? – user1947561 Feb 12 '13 at 04:25
  • Jsonlint can't access the SE api for some reason, it is getting a blank response. Have you checked that the `file_get_contents` call is getting a valid response? You may need to check your [fopen wrappers](http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) settings. – John C Feb 12 '13 at 04:49
  • http://stackoverflow.com/questions/8581924/how-can-i-read-gzip-ed-response-from-stackoverflow-api-in-php – revoua Feb 12 '13 at 04:52

1 Answers1

15

The problem is that the response is also gzipped.

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

<?php
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);
    curl_close($curl);

    return $result;
}


$feed = curl("http://api.stackexchange.com/2.1/users/22656?order=desc&sort=reputation&site=stackoverflow&filter=!*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.

<?php
$feed = file_get_contents('http://api.stackexchange.com/2.1/users/22656?order=desc&sort=reputation&site=stackoverflow&filter=!*MxOyD8qN0Yghnep');
$feed = gzinflate(substr($feed, 10, -8));

$feed = json_decode($feed,true);
$rep = $feed['items'][0]['reputation'];
echo $rep;//531776
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106