doujuan2688 2014-09-28 19:35
浏览 71
已采纳

PHP Multi Curl Request,在等待响应时做一些工作

Here's a typical multi-curl request example for PHP:

$mh = curl_multi_init();

foreach ($urls as $index => $url) {
    $curly[$index] = curl_init($url);
    curl_setopt($curly[$index], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $curly[$index]);
}

// execute the handles
$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while($running > 0);

// get content and remove handles
$result = array();
foreach($curly as $index => $c) {
    $result[$index] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
}

// all done
curl_multi_close($this->mh);

The process involves 3 steps: 1. Preparing data 2. Sending requests and waiting until they're finished 3. Collecting responses

I'd like to split step #2 into 2 parts, first send all the requests and then collect all the response, and do some useful job instead of just waiting, for example, processing the responses of last group of requests.

So, how can I split this part of code

$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while($running > 0);

into separate parts?

  1. Send all the requests
  2. Do some another job while waiting
  3. Retrieve all the responses

I tried like this:

// Send the requests
$running = null;
curl_multi_exec($mh, $running);

// Do some job while waiting
// ...

// Get all the responses
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while($running > 0);

but it doesn't seem to work properly.

  • 写回答

1条回答 默认 最新

  • doumei3828 2014-09-29 07:23
    关注

    I found the solution, here's how to launch all the requests without waiting the response

    do {
        curl_multi_exec($mh, $running);
    } while (curl_multi_select($mh) === -1);
    

    then we can do any other jobs and catch the responses any time later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c