-1

I am attempting to use cURL with the Stack Exchange API but I seem to be getting a null response, any ideas on what's happening?

My code is:

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");
hichris123
  • 10,145
  • 15
  • 56
  • 70

2 Answers2

1

$decoded is an array, so you may use it like this:

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");
HamZa
  • 14,671
  • 11
  • 54
  • 75
1

If you want function json_decode() to return object, you need to omit the second parameter. In your case second parameter is TRUE, which means it will return the array of data.

Also, I'd suggest debugging request by echoing the whole response, not exactly the item you want to see. For example, in case it returns an error.

Ranty
  • 3,333
  • 3
  • 22
  • 24