php curl批量開啟網址(curl_multi類)的實現代碼

來源:互聯網
上載者:User
  1. /*
  2. * curl_multi 經測試,大於四個網址時要比Foreach迴圈快..
  3. * by wc1217
  4. * edit:bbs.it-home.org
  5. */
  6. class curl_multi{
  7. //Curl控制代碼
  8. //private $curl_handle = null;
  9. //網址
  10. private $url_list = array();
  11. //參數
  12. private $curl_setopt = array(
  13. 'CURLOPT_RETURNTRANSFER' => 1, //結果返回給變數
  14. 'CURLOPT_HEADER' => 0, //要HTTP頭不?
  15. 'CURLOPT_NOBODY' => 0, //不要內容?
  16. 'CURLOPT_FOLLOWLOCATION' => 0, //自動跟蹤
  17. 'CURLOPT_TIMEOUT' => 6//逾時(s)
  18. );
  19. function __construct($seconds = 30){
  20. set_time_limit($seconds);
  21. }
  22. /*
  23. * 設定網址
  24. * @list 數組
  25. */
  26. public function setUrlList($list = array()){
  27. $this->url_list = $list;
  28. }
  29. /*
  30. * 設定參數
  31. * @cutPot array
  32. */
  33. public function setOpt($cutPot){
  34. $this->curl_setopt = $cutPot + $this->curl_setopt;
  35. }
  36. /*
  37. * 執行
  38. * @return array
  39. */
  40. public function exec(){
  41. $mh = curl_multi_init();
  42. foreach($this->url_list as $i => $url){
  43. $conn[$i] = curl_init($url);
  44. foreach($this->curl_setopt as $key => $val){
  45. curl_setopt($conn[$i], preg_replace('/(CURLOPT_\w{1,})/ie', '$0', $key), $val);
  46. }
  47. curl_multi_add_handle($mh, $conn[$i]);
  48. }
  49. $active = false;
  50. do{
  51. $mrc = curl_multi_exec($mh, $active);
  52. }while($mrc == CURLM_CALL_MULTI_PERFORM);
  53. while($active and $mrc == CURLM_OK){
  54. if(curl_multi_select($mh) != -1){
  55. do{
  56. $mrc = curl_multi_exec($mh, $active);
  57. }while($mrc == CURLM_CALL_MULTI_PERFORM);
  58. }
  59. }
  60. $res = array();
  61. foreach($this->url_list as $i => $url){
  62. $res[$i] = curl_multi_getcontent($conn[$i]);
  63. curl_close($conn[$i]);
  64. curl_multi_remove_handle($mh, $conn[$i]); //用完馬上釋放資源
  65. }
  66. curl_multi_close($mh);
  67. return $res;
  68. }
  69. }
  70. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.