推荐答案
发送 GET 请求
$url = 'https://example.com/api'; $queryParams = http_build_query(['param1' => 'value1', 'param2' => 'value2']); $fullUrl = $url . '?' . $queryParams; $response = file_get_contents($fullUrl); echo $response;
发送 POST 请求
// www.javascriptcn.com code example
$url = 'https://example.com/api';
$postData = http_build_query(['param1' => 'value1', 'param2' => 'value2']);
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => $postData,
],
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;本题详细解读
GET 请求
GET 请求通常用于从服务器获取数据。在 PHP 中,可以使用 file_get_contents() 函数来发送 GET 请求。首先,构建完整的 URL,包括查询参数,然后使用 file_get_contents() 函数发送请求并获取响应。
POST 请求
POST 请求通常用于向服务器提交数据。在 PHP 中,可以使用 file_get_contents() 函数结合 stream_context_create() 来发送 POST 请求。首先,构建 POST 数据,然后创建一个包含请求头、方法和数据的上下文选项数组。最后,使用 file_get_contents() 函数发送请求并获取响应。
注意事项
- 在使用
file_get_contents()发送请求时,确保allow_url_fopen配置项在php.ini中已启用。 - 对于更复杂的请求(如需要处理 JSON 数据或设置自定义请求头),可以考虑使用
cURL扩展。