如何使
foreach
或 for
循环仅在收到卷曲响应时运行..
例如:
for ($i = 1; $i <= 10; $i++) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://www.example.com");
if(curl_exec($ch)){ // ?? - if request and data are completely received
// ?? - go to the next loop
}
// DONT go to the next loop until the above data is complete or returns true
}
我不希望它在没有收到当前curl请求数据的情况下移动到下一个循环..一个接一个,所以基本上它会在第一次打开url,等待请求数据,如果匹配或成真然后进入下一个循环,
你不必担心“卷曲”部分,我只是想让循环一个接一个地移动(给它一个特定的条件或其他东西)而不是同时移动
循环应该已经这样工作了,因为您使用的是阻塞 cURL 接口,而不是 cURL Multi 接口。
$ch = curl_init();
for ($i = 1; $i <= 10; $i++)
{
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
$res = curl_exec($ch);
// Code checking $res is not false, or, if you returned the page
// into $res, code to check $res is as expected
// If you're here, cURL call completed. To know if successfully or not,
// check $res or the cURL error status.
// Removing the examples below, this code will hit always the same site
// ten times, one after the other.
// Example
if (something is wrong, e.g. False === $res)
continue; // Continue with the next iteration
Here extra code to be executed if call was *successful*
// A different example
if (something is wrong)
break; // exit the loop immediately, aborting the next iterations
sleep(1); // Wait 1 second before retrying
}
curl_close($ch);
在
curl
调用完成之前,您的代码(按原样)不会移至下一次迭代。
需要考虑的几个问题
curl
设置更高的超时时间,以确保没有通信延迟。 CURLOPT_CONNECTTIMEOUT
、CURLOPT_CONNECTTIMEOUT_MS
(毫秒)、CURLOPT_DNS_CACHE_TIMEOUT
、CURLOPT_TIMEOUT
和 CURLOPT_TIMEOUT_MS
(毫秒)可用于增加超时。 0 使 curl
无限期地等待任何这些超时。curl
请求由于某种原因失败,您可以在此处放置 exit
来停止执行,这样它就不会移动到下一个 URL。 continue
控制结构应该就是您正在寻找的:
用于循环结构中,以跳过当前循环迭代的其余部分,并在条件评估时继续执行,然后在下一次迭代开始时继续执行。continue
http://php.net/manual/en/control-structs.continue.php
for ($i = 1; $i <= 10; $i++) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://www.example.com");
if(curl_exec($ch)){ // ?? - if request and data are completely received
continue; // ?? - go to the next loop
}
// DONT go to the next loop until the above data is complete or returns true
}
您可以使用
break
关键字打破循环:
foreach ($list as $thing) {
if ($success) {
// ...
} else {
break;
}
}
for($i = 1; $i <= 10; $i++) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://www.example.com");
if(curl_exec($ch)){ // ?? - if request and data are completely received
continue;
}else{
break;
}
// DONT go to the next loop until the above data is complete or returns true
}
或
for($i = 1; $i <= 10; $i++) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://www.example.com");
if(curl_exec($ch)===false){ // ?? - if request and data are completely received
break;
}
}
这是测试后循环的情况。您实际上想在循环体之后执行条件循环中断 - 使用
do {} while()
。
此结构无条件调用第一次迭代,然后仅在
$result
值为真时继续。
$ch = curl_init();
$i = 1;
do {
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
$result = curl_exec($ch);
++$i;
} while ($result); // add `&& $i <= 10` here, if you actually need it