php curl exec ch,PHP curl_multi_exec函数

PHP curl_multi_exec函数

(PHP 5)

curl_multi_exec — 运行当前 cURL 句柄的子连接

说明

int curl_multi_exec ( resource $mh , int &$still_running )

处理在栈中的每一个句柄。无论该句柄需要读取或写入数据都可调用此方法。

参数

mh

由 curl_multi_init() 返回的 cURL 多个句柄。

still_running

一个用来判断操作是否仍在执行的标识的引用。

返回值

一个定义于 cURL 预定义常量中的 cURL 代码。

注意:

该函数仅返回关于整个批处理栈相关的错误。即使返回 CURLM_OK 时单个传输仍可能有问题。

实例

这个范例将会创建 2 个 cURL 句柄,把它们加到批处理句柄,然后并行地运行它们。

// 创建一对cURL资源

$ch1 = curl_init();

$ch2 = curl_init();

// 设置URL和相应的选项

curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");

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);

$active = null;

// 执行批处理句柄

do {

$mrc = curl_multi_exec($mh, $active);

} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {

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

do {

$mrc = curl_multi_exec($mh, $active);

} while ($mrc == CURLM_CALL_MULTI_PERFORM);

}

}

// 关闭全部句柄

curl_multi_remove_handle($mh, $ch1);

curl_multi_remove_handle($mh, $ch2);

curl_multi_close($mh);

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHPcURL 库提供了一个 `curl_multi_*` 系列的函数,可以实现批量处理多个 cURL 请求。使用 `curl_multi_*` 函数,可以实现在一个 PHP 脚本中同时发送多个 cURL 请求,而不需要等待每个请求的响应。 使用 `curl_multi_*` 函数的步骤如下: 1. 创建多个 cURL 句柄,设置每个句柄的选项。 2. 创建一个 cURL 多个句柄的管理器。 3. 将多个 cURL 句柄添加到管理器中。 4. 执行多个 cURL 句柄,等待所有请求的响应。 5. 处理每个请求的响应。 下面是一个示例代码: ``` <?php // 创建多个 cURL 句柄 $urls = [ 'http://www.example.com', 'http://www.example.net', 'http://www.example.org', ]; $curl_handlers = []; foreach ($urls as $url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $curl_handlers[] = $ch; } // 创建一个 cURL 多个句柄的管理器 $mh = curl_multi_init(); // 将多个 cURL 句柄添加到管理器中 foreach ($curl_handlers as $ch) { curl_multi_add_handle($mh, $ch); } // 执行多个 cURL 句柄,等待所有请求的响应 $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) == -1) { usleep(100); } do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } // 处理每个请求的响应 foreach ($curl_handlers as $ch) { $output = curl_multi_getcontent($ch); curl_multi_remove_handle($mh, $ch); curl_close($ch); // 处理响应 echo $output; } curl_multi_close($mh); ``` 上述代码将创建多个 cURL 句柄,将它们添加到一个 cURL 多个句柄的管理器中,然后使用 `curl_multi_exec()` 函数并通过 `curl_multi_select()` 函数等待所有请求的响应。最后,使用 `curl_multi_getcontent()` 函数获取每个请求的响应,并处理它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值