php 实现get请求
使用 cURL 发起 GET 请求
通过 PHP 的 cURL 扩展可以方便地发起 HTTP GET 请求。以下是一个基本示例:
$url = 'https://example.com/api';
$params = ['key1' => 'value1', 'key2' => 'value2'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
使用 file_get_contents 发起 GET 请求
对于简单的 GET 请求,可以使用 PHP 内置的 file_get_contents 函数:
$url = 'https://example.com/api';
$params = ['key1' => 'value1', 'key2' => 'value2'];
$fullUrl = $url . '?' . http_build_query($params);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-type: application/x-www-form-urlencoded'
]
]);
$response = file_get_contents($fullUrl, false, $context);
echo $response;
使用 Guzzle HTTP 客户端
Guzzle 是一个流行的 PHP HTTP 客户端,可以简化 HTTP 请求的处理:
require 'vendor/autoload.php';
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://example.com/api', [
'query' => ['key1' => 'value1', 'key2' => 'value2']
]);
echo $response->getBody();
使用 PHP 内置的 HTTP 上下文
PHP 的流上下文可以用于创建自定义的 HTTP 请求:
$url = 'https://example.com/api';
$params = ['key1' => 'value1', 'key2' => 'value2'];
$fullUrl = $url . '?' . http_build_query($params);
$options = [
'http' => [
'method' => 'GET',
'header' => "Accept: application/json\r\n"
]
];
$context = stream_context_create($options);
$response = file_get_contents($fullUrl, 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);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
echo $response;






