1. <?php
  2. /*
  3. * curl_multi 经测试,大于四个网址时要比Foreach循环快..
  4. * by wc1217
  5. * edit:bbs.it-home.org
  6. */
  7. class curl_multi{
  8. //Curl句柄
  9. //private $curl_handle = null;
  10. //网址
  11. private $url_list = array();
  12. //参数
  13. private $curl_setopt = array(
  14. ‘CURLOPT_RETURNTRANSFER’ => 1, //结果返回给变量
  15. ‘CURLOPT_HEADER’ => 0, //要HTTP头不?
  16. ‘CURLOPT_NOBODY’ => 0, //不要内容?
  17. ‘CURLOPT_FOLLOWLOCATION’ => 0, //自动跟踪
  18. ‘CURLOPT_TIMEOUT’ => 6//超时(s)
  19. );
  20. function __construct($seconds = 30){
  21. set_time_limit($seconds);
  22. }
  23. /*
  24. * 设置网址
  25. * @list 数组
  26. */
  27. public function setUrlList($list = array()){
  28. $this->url_list = $list;
  29. }
  30. /*
  31. * 设置参数
  32. * @cutPot array
  33. */
  34. public function setOpt($cutPot){
  35. $this->curl_setopt = $cutPot + $this->curl_setopt;
  36. }
  37. /*
  38. * 执行
  39. * @return array
  40. */
  41. public function exec(){
  42. $mh = curl_multi_init();
  43. foreach($this->url_list as $i => $url){
  44. $conn[$i] = curl_init($url);
  45. foreach($this->curl_setopt as $key => $val){
  46. curl_setopt($conn[$i], preg_replace(‘/(CURLOPT_\w{1,})/ie’, ‘$0’, $key), $val);
  47. }
  48. curl_multi_add_handle($mh, $conn[$i]);
  49. }
  50. $active = false;
  51. do{
  52. $mrc = curl_multi_exec($mh, $active);
  53. }while($mrc == CURLM_CALL_MULTI_PERFORM);
  54. while($active and $mrc == CURLM_OK){
  55. if(curl_multi_select($mh) != -1){
  56. do{
  57. $mrc = curl_multi_exec($mh, $active);
  58. }while($mrc == CURLM_CALL_MULTI_PERFORM);
  59. }
  60. }
  61. $res = array();
  62. foreach($this->url_list as $i => $url){
  63. $res[$i] = curl_multi_getcontent($conn[$i]);
  64. curl_close($conn[$i]);
  65. curl_multi_remove_handle($mh, $conn[$i]); //用完马上释放资源
  66. }
  67. curl_multi_close($mh);
  68. return $res;
  69. }
  70. }
  71. ?>

复制代码