-1

我正在尝试将 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");
4

2 回答 2

1

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

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

于 2012-12-09T10:20:52.623 回答
1

$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");
于 2012-12-08T23:16:39.923 回答