Getting null as response from Stack Overflow API with PHP

帅比萌擦擦* 提交于 2019-12-21 05:22:00

问题


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?


回答1:


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
?>


来源:https://stackoverflow.com/questions/14825188/getting-null-as-response-from-stack-overflow-api-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!