函数名:curl_multi_getcontent()
适用版本:PHP 5, PHP 7
用法:curl_multi_getcontent() 函数用于获取在使用 curl_multi_* 函数进行并行请求时,单个请求的响应内容。
语法:string curl_multi_getcontent(resource $ch)
参数:
- $ch: 必需。一个 cURL 句柄,由 curl_init() 函数返回。
返回值:返回 string 类型的响应内容,如果没有内容则返回空字符串。
示例:
// 创建两个 cURL 句柄
$ch1 = curl_init();
$ch2 = curl_init();
// 设置两个请求的 URL
curl_setopt($ch1, CURLOPT_URL, 'https://example.com/api1');
curl_setopt($ch2, CURLOPT_URL, 'https://example.com/api2');
// 创建 cURL 多处理句柄
$mh = curl_multi_init();
// 添加两个句柄到多处理句柄
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);
// 执行多个 cURL 请求
$active = null;
do {
$status = curl_multi_exec($mh, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);
// 检查错误
if ($status !== CURLM_OK) {
// 错误处理
}
// 获取第一个请求的响应内容
$response1 = curl_multi_getcontent($ch1);
echo $response1;
// 获取第二个请求的响应内容
$response2 = curl_multi_getcontent($ch2);
echo $response2;
// 移除和关闭句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
注意事项:
- 在使用 curl_multi_getcontent() 函数获取响应内容之前,确保相关请求已经执行完毕。
- 如果需要获取多个请求的响应内容,可以使用类似上面示例中的方式进行遍历。