获取null作为从PHP堆栈溢出API响应(Getting null as response fro

2019-08-16 21:39发布

我用这个代码PHP获取堆栈溢出的声誉。

$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;

但是我得到null作饲料。 同时用户帐户是乔恩斯基特这就是我得到的ID 22656.我怎样才能解决这个问题?

Answer 1:

问题是,该反应也gzip压缩。

我首选的解决将是使用卷曲,以CURLOPT_ENCODING选项。

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

虽然,你可以正常使用FGC,然后膨胀响应回解压缩。

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


文章来源: Getting null as response from Stack Overflow API with PHP