Freebase API call works in browser but fails with curl

大憨熊 提交于 2019-12-07 16:50:06

问题


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



来源:https://stackoverflow.com/questions/15250069/freebase-api-call-works-in-browser-but-fails-with-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!