函式名稱:curl_multi_select()
適用版本:PHP 5, PHP 7
函式說明:curl_multi_select() 函式等待直到相應 cURL 多個控制代碼有資料可讀或出現錯誤時,或者在指定的超時時間到期之前。此函式用於與 curl_multi_exec() 結合使用,以解決非阻塞式 curl 多個請求的等待問題。
用法: int curl_multi_select(resource $mh[, float $timeout = 1.0])
引數:
- $mh:cURL 多個控制代碼的資源。
- $timeout:可選引數,指定超時時間,單位為秒,預設為 1.0 秒。
返回值: 成功時返回活動描述符的數目,出現錯誤時返回 -1。
示例:
<?php
$mh = curl_multi_init(); // 初始化 cURL 多個控制代碼
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/api1");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch1);
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, "http://www.example.com/api2");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch2);
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
// 使用 curl_multi_select() 等待直到有資料可讀或出現錯誤
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);
// 獲取 ch1 的響應資料
$response1 = curl_multi_getcontent($ch1);
// 獲取 ch2 的響應資料
$response2 = curl_multi_getcontent($ch2);
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
// 處理響應資料
echo "Response from API1: " . $response1;
echo "Response from API2: " . $response2;
?>
上述示例程式碼展示了使用 curl_multi_select() 函式與 curl_multi_exec() 結合使用的方式。在該示例中,我們使用 curl_multi_init() 初始化 cURL 多個控制代碼,並將多個控制代碼新增到 cURL 多個控制代碼集合中。
在執行 curl_multi_exec() 時,如果仍有活動的請求,使用 curl_multi_select() 函式來等待資料可讀或出現錯誤。然後透過 curl_multi_getcontent() 函式獲取每個請求的響應資料。
最後,移除控制代碼並關閉 cURL 多個控制代碼集合。
請注意,上述示例僅用於展示 curl_multi_select() 的基本用法,實際使用中可能需要根據具體需求進行適當的調整。
熱門工具排行榜