php curl multi,php multi curl

本文介绍了一个使用PHP实现的多路并发cURL请求处理函数,通过curl_multi_init等函数实现对多个URL的并发请求,提高了网络请求效率。该函数支持设置默认选项,并能获取所有请求的响应结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function multiCurl($res,$options=""){

if(count($res)<=0) return False;

$handles = array();

if(!$options) // add default options

$options = array(

CURLOPT_HEADER=>0,

CURLOPT_RETURNTRANSFER=>1,

);

// add curl options to each handle

foreach($res as $k=>$row){

$ch{$k} = curl_init();

$options[CURLOPT_URL] = $row['url'];

curl_setopt_array($ch{$k}, $options);

$handles[$k] = $ch{$k};

}

$mh = curl_multi_init();

foreach($handles as $k => $handle){

curl_multi_add_handle($mh,$handle);

//echo "
adding handle {$k}";

}

$running_handles = null;

//execute the handles

$cme=null;

$status=null;

do {

$status_cme = curl_multi_exec($mh, $running_handles);

} while ($cme == CURLM_CALL_MULTI_PERFORM);

while ($running_handles && $status_cme == CURLM_OK) {

if (curl_multi_select($mh) != -1) {

do {

$status_cme = curl_multi_exec($mh, $running_handles);

// echo "
''threads'' running = {$running_handles}";

} while ($status == CURLM_CALL_MULTI_PERFORM);

}

}

foreach($res as $k=>$row){

$res[$k]['error'] = curl_error($handles[$k]);

if(!empty($res[$k]['error']))

$res[$k]['data']  = '';

else

$res[$k]['data']  = curl_multi_getcontent( $handles[$k] );  // get results

// close current handler

curl_multi_remove_handle($mh, $handles[$k] );

}

curl_multi_close($mh);

return $res; // return response

}

$res = array(

"11"=>array("url"=>"http://api.211.100.56.140.xip.io/shows.json/263?appKey=strKfLS2Hecp"),

"12"=>array("url"=>"http://api.211.100.56.140.xip.io/shows.json/263?appKey=strKfLS2Hecp"),

);

print_r(multiCurl($res));

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值