【问题标题】:Can't get data from Stack Exchange API无法从 Stack Exchange API 获取数据
【发布时间】:2014-02-27 14:03:33
【问题描述】:
我正在尝试从http://api.stackoverflow.com/1.1/search?tagged=php 获取数据。
我正在使用此代码从 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);
但它什么也没显示。我也使用 curl 来获取数据,但它也没有显示任何内容。为什么它没有向我显示任何内容,我该如何解决?
【问题讨论】:
标签:
php
json
curl
stackexchange-api
【解决方案1】:
他们将 gzip 压缩后的内容作为响应返回给您。这就是为什么它不适用于您的 json 解码。这是等效的 curl 请求。
$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】:
响应被压缩,使用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);