函式名: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() 函式獲取響應內容之前,確保相關請求已經執行完畢。
- 如果需要獲取多個請求的響應內容,可以使用類似上面示例中的方式進行遍歷。