php实现get请求
PHP 实现 GET 请求的方法
使用 file_get_contents 函数
通过 file_get_contents 函数可以简单实现 GET 请求。此方法适用于简单的请求场景,但不支持复杂的请求头设置。
$url = 'http://example.com/api?param1=value1¶m2=value2';
$response = file_get_contents($url);
echo $response;
使用 curl 扩展
curl 是更强大的工具,支持自定义请求头、超时设置等功能。
$url = 'http://example.com/api?param1=value1¶m2=value2';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
添加请求头
通过 curl 可以方便地添加请求头。
$url = 'http://example.com/api';
$headers = [
'Authorization: Bearer token123',
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
处理 URL 参数
使用 http_build_query 可以自动构建 URL 查询字符串。
$params = [
'param1' => 'value1',
'param2' => 'value2',
];
$query = http_build_query($params);
$url = 'http://example.com/api?' . $query;
$response = file_get_contents($url);
echo $response;
错误处理
在使用 curl 时,建议添加错误处理逻辑。
$url = 'http://example.com/api';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo $response;
}
curl_close($ch);
使用 stream_context_create 设置选项
如果需要通过 file_get_contents 设置请求头或其他选项,可以使用 stream_context_create。
$url = 'http://example.com/api';
$options = [
'http' => [
'method' => 'GET',
'header' => "Authorization: Bearer token123\r\n",
],
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
以上方法覆盖了从简单到复杂的 GET 请求实现,可以根据实际需求选择适合的方式。







