Can't get data from Stack Exchange API

戏子无情 提交于 2019-12-02 06:54:22

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/22070864/cant-get-data-from-stack-exchange-api

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