-->

Freebase API call works in browser but fails with

2019-05-10 08:54发布

问题:

I'm trying to receive data from the Freebase API. I manually built a working API call which gave me a valid JSON response in my browser. So I wrote a PHP Function which should do exactly that:

$service_url = 'https://www.googleapis.com/freebase/v1/search';
$params = array(
           'filter' => '(all name:"Avatar")',
           'lang' => 'en',
           'type' => 'film/film',
           'key' => Configure::read('Api.Key')
         );
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);

The response I get is NULL, but if I take the built URL and enter it into my Chrome REST Plugin or view it directly in the browser, I get a valid response. If the url is valid, why would my curl function fail?

回答1:

For me by adding the below line worked.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 


回答2:

My guess is that you are seeing NULL because the curl_exec returns false and then the json_decode converts the false to NULL.

This means, as you suspected, that curl_exec is failing. I'm not sure why, but I would start by debugging with curl_error() and curl_errno() to get more information on what is causing curl to fail.

Reference: curl_exec() always returns false