【发布时间】:2012-03-11 21:31:19
【问题描述】:
根据 Google 自定义搜索 API 的描述,您可以使用 REST 接口的 GET 动词调用它,如示例:
GET https://www.googleapis.com/customsearch/v1?key=INSERT-YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=lectures
我设置了我的 API 密钥和自定义搜索引擎,当我直接将我的测试查询粘贴到我的浏览器上时,它运行良好,并且我得到了显示给我的 JSON 文件。
然后我尝试使用以下方法从我的 PHP 代码中调用 API:
$json = file_get_contents("$url") or die("failed");
其中 $url 与在浏览器上运行的相同,但我的 PHP 代码在尝试打开它时死掉了。
之后我尝试使用 curl,它成功了。代码是这样的:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$body = curl_exec($ch);
问题:
- 为什么 file_get_contents() 不起作用而 curl 起作用?
- 我也可以使用 fsocket 吗?
【问题讨论】:
-
可能是因为您的 PHP 设置已设置为不允许使用 fopen 包装器进行远程连接:uk3.php.net/manual/en/…
-
我可以用 file_get_contents 打开其他页面,就像这个工作一样 $test = file_get_contents("google.com");