无阻塞地返回异步请求

时间:2014-04-30 09:23:02

标签: php curl curl-multi

我能够使用curl_multi实现curl请求的并行执行。但是我对这个回复有疑问。即使请求并行执行,只有在执行了所有URL后才会收到响应。

我的要求是在每个请求执行后立即返回响应。

有人能指出解决方案吗?

<?php
$price  = urlencode("select * from html where url=\"http://www.flipkart.com/karwar- cuisine-traditional-recipes-small-coastal-town-karnataka/p/itmdfrx4z4erg9ya?pid=9788179917558\" and xpath=\"//span[contains(@class,'pprice')]/text()\"");

$desc   = urlencode("select * from html where url=\"http://www.flipkart.com/karwar-cuisine-traditional-recipes-small-coastal-town-karnataka/p/itmdfrx4z4erg9ya?pid=9788179917558\" and xpath=\"//div[@class='item_desc_text line']\"");

$author = urlencode("select * from html where url=\"http://www.flipkart.com/karwar-cuisine-traditional-recipes-small-coastal-town-karnataka/p/itmdfrx4z4erg9ya?pid=9788179917558\" and xpath=\"//div[contains(@class,'secondary-info')]//a/text()\"");

$title  = urlencode("select * from html where url=\"http://www.flipkart.com/karwar-cuisine-traditional-recipes-small-coastal-town-karnataka/p/itmdfrx4z4erg9ya?pid=9788179917558\" and xpath=\"//div[contains(@class,'mprod-summary-title')]//h1/text()\"");

$url1 = "https://query.yahooapis.com/v1/public/yql?q={$price}&format=json";
$url2 = "https://query.yahooapis.com/v1/public/yql?q={$desc}&format=json";
$url3 = "https://query.yahooapis.com/v1/public/yql?q={$author}&format=json";
$url4 = "https://query.yahooapis.com/v1/public/yql?q={$title}&format=json";

$nodes      = array(
$url1,
$url2,
$url3,
$url4
);
$node_count = count($nodes);

$curl_arr = array();
$master   = curl_multi_init();

for ($i = 0; $i < $node_count; $i++) {
$url          = $nodes[$i];
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($master, $curl_arr[$i]);
}

do {
curl_multi_exec($master, $running);
} while ($running > 0);


for ($i = 0; $i < $node_count; $i++) {
$results[] = curl_multi_getcontent($curl_arr[$i]);
}
print_r($results);

?>

1 个答案:

答案 0 :(得分:0)

只要还有任何传输仍然未决,你的循环就会一直运行!

(它忙碌循环所以它总是使用100%CPU ...)