Can't get data from Stack Exchange API

2019-08-12 16:50发布

I am trying to get data from http://api.stackoverflow.com/1.1/search?tagged=php .

I am using this code to get data from the API:

$url = "http://api.stackoverflow.com/1.1/search?tagged=php";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
print_r($json);

But it is showing me nothing. I have also used curl to get the data, but it also shows nothing. Why isn't it showing me anything, and how can I fix that?

2条回答
▲ chillily
2楼-- · 2019-08-12 17:05

The response is gzipped, use gzdecode :

$url = "http://api.stackoverflow.com/1.1/search?tagged=php";
$json = file_get_contents($url);
$json_data = json_decode(gzdecode($json), true);
print_r($json);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-12 17:15

They are returning you gzipped content as response. That's why it didn't work with your json decoding. Here is equivalent curl request.

$url= "http://api.stackoverflow.com/1.1/search?tagged=php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_ENCODING, ""); // this will handle gzip content
$result = curl_exec($ch);
curl_close($ch);
print $result;
// do json processing here
查看更多
登录 后发表回答