使用file_get_contents发送x-openaip-client-id标识的API密钥可行吗?
使用file_get_contents对接OpenAIP API是否可行?
我尝试对接的API使用标识为
x-openaip-client-id的API密钥,编写了如下PHP代码:<?php $countryCode = "DE"; $token = "fsdfdsf"; $url = "https://api.core.openaip.net/api/airspaces?type=4&country=" . $countryCode; $options = array('http' => array( 'method' => 'GET', 'header' => 'Authorization: x-openaip-client-id '.$token )); $context = stream_context_create($options); $raw = file_get_contents($url, false, $context); $array = json_decode($raw); print("<pre>".print_r($array,true)."</pre>"); ?>请问通过这种方式使用
file_get_contents()是否可行?还是必须改用curl或类似组件?相关文档参考OpenAIP官方文档。
结论与分析
1. 这种写法完全可行
你的代码逻辑没问题:通过stream_context_create()配置带授权头的HTTP请求参数,再用file_get_contents()发送GET请求,这是PHP中发起HTTP请求的标准方式之一,只要满足两个前提就能正常工作:
- 服务器PHP配置里的
allow_url_fopen是开启状态(默认一般都开着); - 请求超时时间足够覆盖API响应时长(可通过
default_socket_timeout调整)。
2. 要不要改用curl?看需求
如果只是简单的GET请求,当前写法足够用,但如果碰到以下情况,curl会更靠谱:
- 服务器禁用了
allow_url_fopen:这是部分主机的安全配置,此时curl是唯一可行的HTTP请求工具; - 需要复杂请求控制:比如自定义超时、处理HTTPS证书、发送POST/PUT等非GET请求;
- 需排查错误:curl能返回详细的错误码和信息,方便定位请求失败原因(比如网络不通、密钥无效);
- 处理大响应:curl支持流式读取,避免
file_get_contents()一次性加载大数据占满内存。
3. 对应的curl版本代码示例
如果要切换到curl,代码可以这么写:
<?php $countryCode = "DE"; $token = "fsdfdsf"; $url = "https://api.core.openaip.net/api/airspaces?type=4&country=" . $countryCode; // 初始化curl会话 $ch = curl_init($url); // 设置请求头 curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: x-openaip-client-id ' . $token ]); // 要求返回响应内容而非直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 可选:设置10秒超时 curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 执行请求 $raw = curl_exec($ch); // 获取响应状态码 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 关闭会话 curl_close($ch); // 处理结果 if ($raw === false) { echo "请求出错:" . curl_error($ch); } else { $array = json_decode($raw); print("<pre>" . print_r($array, true) . "</pre>"); } ?>
内容的提问来源于stack exchange,提问作者Matt Welander
相关产品推荐
相关产品推荐

