【问题标题】:PHP Multi Curl Request, do some job while waiting the responsePHP Multi Curl Request,在等待响应时做一些工作
【发布时间】:2014-09-28 19:35:38
【问题描述】:

这是一个典型的 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);

该过程涉及 3 个步骤: 1. 准备数据 2.发送请求并等待它们完成 3. 收集回复

我想将第 2 步拆分为 2 个部分,首先发送所有请求,然后收集所有响应,并做一些有用的工作,而不是仅仅等待,例如处理最后一组请求的响应。

那么,我该如何拆分这部分代码

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

分成不同的部分?

  1. 发送所有请求
  2. 在等待的时候做一些其他的工作
  3. 检索所有响应

我试过这样:

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

但它似乎无法正常工作。

【问题讨论】:

  • 您能否描述更多“似乎无法正常工作”的内容?
  • 响应在第二个周期(do ... while)中还没有准备好,即使在它之前放置了 sleep(10)。您可以自己运行代码,看看它没有按预期工作。

标签: php curl


【解决方案1】:

我找到了解决方案,这里是如何在不等待响应的情况下启动所有请求

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

然后我们可以做任何其他工作并在以后的任何时间捕捉响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2021-11-05
    • 2011-12-22
    • 2016-08-29
    • 2020-02-02
    • 1970-01-01
    相关资源
    最近更新 更多