如果你想用PHP访问API,file_get_contents还不够吗?

你好。
我是Mandai,负责Wild 开发团队。
你熟悉 PHP 的 `file_get_contents` 方法吗?
它非常实用,因为它能让你简洁地编写文件打开流程,但除了读取文件之外,它还可以用作简单的网页访问工具。
今天,我想探讨一下它的用途局限性。
file_get_contents 基础知识
举个简单的例子,要获取我们公司的主页,源代码看起来会是这样:
<?php $html = file_get_contents('https://beyondjapan.com');
这样应该没问题。
如果不行,请确保你的 php.ini 文件中允许 url_fopen:
allow_url_fopen = 开启
file_get_contents 的应用
`file_get_contents` 方法不仅可以获取 HTML 文件。
接下来,我们尝试使用 `stream_context_create` 方法发送 POST 请求。
如果你查看 stream_context_create 方法的手册,它只简单地写道“创建流上下文”。
通过操作这个流上下文,你就可以发送 POST 请求。
<?php $data = [ 'title' =>'发送测试', 'body' => 'test', ]; $opts = [ 'http' => [ 'method' => 'POST', 'header' => implode("\r\n", [ "User-Agent: hogehoge", "Accept-Language: ja", "Cookie: test=hoge", ]), ], 'data' => http_build_query($data) ]; $ctx = stream_context_create($opts); $response = file_get_contents('http://example.com/inquiry', false, $ctx);
您希望通过 POST 发送的数据应该使用 http_build_query 进行 URL 编码并转换为查询字符串。
对于 JSON 数据,您应该先使用 json_encode 方法对其进行编码,然后再使用 urlencode 方法进行 URL 编码。
file_get_contents 的真实值
如前例所示,您可以在流上下文中创建标头信息,因此您可以根据需要使用 Cookie!
您还可以绕过基本身份验证并使用会话浏览网站。
它还支持将 API 密钥嵌入到标头信息中的 API,例如 Chatwork API。
如果要使用 SSL 通信,无需过多考虑;只需将协议指定为“https://”即可。
这就是我想表达的意思,所以我写了这篇博客。
即使没有安装 php-curl 的环境中,file_get_contents 也能正常工作,因此它可以作为 curl 库的替代方案
(当然,curl 的功能更强大)
就是这样。
2