當PHP使用多線程版本的cURL時可以提高很多效率,但是按照很多地方都給出了這個例子(http://cn2.php.net/manual/zh/function.curl-multi-exec.php)
1 <?php 2 // 創建一對cURL資源 3 $ch1 = curl_init(); 4 $ch2 = curl_init(); 5 6 // 設置URL和相應的選項 7 curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/"); 8 curl_setopt($ch1, CURLOPT_HEADER, 0); 9 curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/"); 10 curl_setopt($ch2, CURLOPT_HEADER, 0); 11 12 // 創建批處理cURL句柄 13 $mh = curl_multi_init(); 14 15 // 增加2個句柄 16 curl_multi_add_handle($mh,$ch1); 17 curl_multi_add_handle($mh,$ch2); 18 19 $active = null; 20 // 執行批處理句柄 21 do { 22 $mrc = curl_multi_exec($mh, $active); 23 } while ($mrc == CURLM_CALL_MULTI_PERFORM); 24 25 while ($active && $mrc == CURLM_OK) { 26 if (curl_multi_select($mh) != -1) { 27 do { 28 $mrc = curl_multi_exec($mh, $active); 29 } while ($mrc == CURLM_CALL_MULTI_PERFORM); 30 } 31 } 32 33 // 關閉全部句柄 34 curl_multi_remove_handle($mh, $ch1); 35 curl_multi_remove_handle($mh, $ch2); 36 curl_multi_close($mh); 37 38 ?>
需要注意的是第26行代碼,在我的機器環境下(PHP 5.3.13),curl_multi_select函數會一直返回-1,形成成死循環,去掉就好了。