如何在PHP中使用Stack Overflow API [英] How to use Stack Overflow API in PHP
问题描述
我有以下网址:
当我在浏览器的地址栏中键入该URL时,它会给我一个JSON响应,这在PHP中是必需的.我尝试使用cURL来获取它(请参见下面的代码),但是它不起作用—没有响应打印在页面上.
When I type this URL in my browser's address bar, it gives me a JSON response, which I need in PHP. I tried using cURL to fetch it (see below code), but it didn't work — no response is printed on the page.
function get_json($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($resultCode == 200) {
return json_decode($data);
} else {
return false;
}
}
$json = get_json('https://api.stackexchange.com/2.0/questions?page=1&pagesize=30&
key=VVq3kJHSjQ*7qgpiRaVoLA%28%28&site=stackoverflow');
echo '<pre>';
print_r($json);
如何获取此URL并将其正确转换为PHP数组?
How can I fetch this URL and convert it into a PHP array the right way?
推荐答案
最后我检查了一下,API的所有响应均经过gzip压缩:
Last I checked, all responses from the API were gzip'd:
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url
, CURLOPT_HEADER => 0
, CURLOPT_RETURNTRANSFER => 1
, CURLOPT_ENCODING => 'gzip'
));
$data = curl_exec($ch);
var_dump($data);
var_dump(json_decode($data));
设置CURLOPT_ENCODING
可以使响应自动解压缩,除了在http请求中发送Accept-Encoding: gzip
之外,尽管发送该标头并非严格要求,但可以正常工作.
Setting CURLOPT_ENCODING
enables automatic un gzip'ing of the response, in addition to sending an Accept-Encoding: gzip
in the http request, although sending that header isn't strictly required for this to work.
这篇关于如何在PHP中使用Stack Overflow API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!