卷曲多个url调用方法在localhost中不起作用

时间:2018-01-13 12:36:44

标签: php php-curl curl-multi

我有3个curl调用facebook graph API来使用ajax获取数据。对于3次调用,加载数据需要花费太多时间,因此我尝试使用curl多URL调用方法(如curl_multi_init())来异步调用这些URL。

但是在我的localhost测试环境中看起来没什么用。我通过xampp 1.8设置了本地开发环境。当我在在线服务器上尝试时,它正在工作。但只有单个curl调用才能在localhost上运行。这是我的代码。我只是为测试添加了一个测试URL:

$urls = array(); 
$url = "http://codeproject.com";
$urls[0] = $url; $urls[1] = $url; 
// make sure the rolling window isn't greater than the # of urls
$rolling_window = 5;
$rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

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

// add additional curl options here
$std_options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 5);
$options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

// start the first batch of requests
for ($i = 0; $i<$rolling_window; $i++) {
    $ch = curl_init();
    $options[CURLOPT_URL] = $urls[$i];
    curl_setopt_array($ch,$options);
    curl_multi_add_handle($master, $ch);
}

do {
    while(($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
    if($execrun != CURLM_OK)
        break;
        // a request was just completed -- find out which one
        while($done = curl_multi_info_read($master)) {
            $info = curl_getinfo($done['handle']);
            if ($info['http_code'] == 200)  {
                $output = curl_multi_getcontent($done['handle']);                                       
                // request successful.  process output using the callback function.
                    //$callback($output);
                    echo $output; //test

                // start a new request (it's important to do this before removing the old one)
                $ch = curl_init();
                $options[CURLOPT_URL] = $urls[$i++];  // increment i
                curl_setopt_array($ch,$options);
                curl_multi_add_handle($master, $ch);

                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done['handle']);
            } else {
                 //request failed.  add error handling.
            }
        }
} while ($running);

curl_multi_close($master); 

0 个答案:

没有答案