file_get_contents() 与 curl 使用 PHP 调用 API [英] file_get_contents() vs. curl for invoking APIs with PHP
问题描述
根据 Google 自定义搜索 API 的描述,您可以使用 REST 接口的 GET 动词来调用它,例如:
According to the description of the Google Custom Search API you can invoke it using the GET verb of the REST interface, like with the example:
GET https://www.googleapis.com/customsearch/v1?key=INSERT-YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=lectures
我设置了我的 API 密钥和自定义搜索引擎,将我的测试查询直接粘贴到我的浏览器上时,它运行良好,并且我向我显示了 JSON 文件.
I setup my API key and custom search engine, and when pasted my test query directly on my browser it worked fine, and I got the JSON file displayed to me.
然后我尝试使用以下方法从我的 PHP 代码调用 API:
Then I tried to invoke the API from my PHP code by using:
$json = file_get_contents("$url") or die("failed");
其中 $url 与浏览器上运行的相同,但我的 PHP 代码在尝试打开它时死掉了.
Where $url was the same one that worked on the browser, but my PHP code was dying when trying to open it.
在那之后,我尝试使用 curl,它奏效了.代码是这样的:
After that I tried with curl, and it worked. The code was this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$body = curl_exec($ch);
问题:
- 为什么 file_get_contents() 不起作用而 curl 起作用了?
- 我也可以为此使用 fsocket 吗?
推荐答案
问题 1:
首先你应该检查ini设置allow_url_fopen
,AFAIK 这是 file_get_contents()
不应该工作的唯一原因.不推荐使用的 safe_mode
也可能导致这种情况.
Question 1:
At first you should check ini setting allow_url_fopen
, AFAIK this is the only reason why file_get_contents()
shouldn't work. Also deprecated safe_mode
may cause this.
哦,根据您的评论,在使用 文件系统 函数,它是一个 包装器告诉php你需要使用http请求,没有它的功能认为你需要打开./google.com
(与google.txt
相同)).
Oh, based on your comment, you have to add http://
to URL when using with file system functions, it's a wrapper that tells php that you need to use http request, without it function thinks you require to open ./google.com
(the same as google.txt
).
是的,您几乎可以使用套接字构建任何 cURL 请求.
Yes, you can build almost any cURL request with sockets.
我个人的意见是你应该坚持使用 cURL,因为:
My personal opinion is that you should stick with cURL because:
- 超时设置
- 处理所有可能的 HTTP 状态
- 简单而详细的配置(无需详细了解 HTTP 标头)
这篇关于file_get_contents() 与 curl 使用 PHP 调用 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!