(PHP 5)
curl_multi_init — 返回一个新cURL批处理句柄
允许并行地处理批处理cURL句柄。
此函数没有参数。
成功时返回一个cURL批处理句柄,失败时返回FALSE
。
Example #1 curl_multi_init() example
这个范例将会创建2个cURL句柄,把它们加到批处理句柄,然后并行地运行它们。
<?php
// 创建一对cURL资源
$ch1 = curl_init();
$ch2 = curl_init();
// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);
// 创建批处理cURL句柄
$mh = curl_multi_init();
// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
$running=null;
// 执行批处理句柄
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while ($running > 0);
// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>
hushuilong at gmail dot com (2011-08-05 00:21:31)
Simulate multiple threads request:
<?php
function multiple_threads_request($nodes){
$mh = curl_multi_init();
$curl_array = array();
foreach($nodes as $i => $url)
{
$curl_array[$i] = curl_init($url);
curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $curl_array[$i]);
}
$running = NULL;
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while($running > 0);
$res = array();
foreach($nodes as $i => $url)
{
$res[$url] = curl_multi_getcontent($curl_array[$i]);
}
foreach($nodes as $i => $url){
curl_multi_remove_handle($mh, $curl_array[$i]);
}
curl_multi_close($mh);
return $res;
}
print_r(muti_thread_request(array(
'http://www.example.com',
'http://www.example.net',
)));
?>
jaisen at jmathai dot com (2008-05-30 00:09:12)
http://github.com/jmathai/epicode/tree/master/php/EpiCurl.php
If you fire off 10 curl requests in parallel you don't have to wait for all of them to be finished before accessing one which is already finished.