php 实现get请求
使用 cURL 实现 GET 请求
通过 cURL 扩展可以发送 HTTP GET 请求。以下是一个基本示例:
$url = 'https://example.com/api';
$queryParams = ['param1' => 'value1', 'param2' => 'value2'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($queryParams));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
使用 file_get_contents 实现 GET 请求
对于简单的 GET 请求,可以使用 file_get_contents 函数:
$url = 'https://example.com/api?param1=value1¶m2=value2';
$response = file_get_contents($url);
echo $response;
使用 Guzzle HTTP 客户端
Guzzle 是一个流行的 PHP HTTP 客户端库,可以更简洁地发送 GET 请求:
require 'vendor/autoload.php';
$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/api', [
'query' => ['param1' => 'value1', 'param2' => 'value2']
]);
echo $response->getBody();
使用 HTTP 上下文选项
通过 stream_context_create 可以设置 HTTP 请求的上下文选项:
$url = 'https://example.com/api';
$options = [
'http' => [
'method' => 'GET',
'header' => "Content-Type: application/json\r\n"
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
处理 HTTPS 请求
对于 HTTPS 请求,可能需要额外配置 SSL 验证:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 验证(仅测试环境使用)
$response = curl_exec($ch);
curl_close($ch);
添加请求头
在 GET 请求中添加自定义请求头:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer token123',
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
每种方法适用于不同的场景,cURL 提供了最全面的功能,而 file_get_contents 适用于简单的请求。Guzzle 则提供了更现代化的 API 和更好的可维护性。







