Stack Exchange API cURL



我正在尝试将cURL与Stack Exchange API一起使用,但我似乎得到了一个空响应,关于发生了什么有什么想法吗?

我的代码是:

function get($get){
        $ch = curl_init("http://api.stackoverflow.com/1.1/search?intitle=meteor");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        $decoded =  json_decode(curl_exec($ch), true);
        var_dump($decoded->questions[0]->title);
}
get("stackoverflow");

$decoded是一个

数组,所以你可以像这样使用它:

function get($get){
        $ch = curl_init("http://api.stackoverflow.com/1.1/search?intitle=$get");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        $decoded =  json_decode(curl_exec($ch), true);
        echo $decoded["questions"][0]["title"];
}
get("meteor");
如果你想让

函数json_decode()返回对象,你需要省略第二个参数。在您的情况下,第二个参数是 TRUE ,这意味着它将返回数据数组。

此外,我建议通过回显整个响应来调试请求,而不是您想要看到的项目。例如,如果它返回错误。

最新更新