Rumah > pembangunan bahagian belakang > tutorial php > php curl批量打开网址(curl_multi类)的实现代码

php curl批量打开网址(curl_multi类)的实现代码

WBOY
Lepaskan: 2016-07-25 08:55:05
asal
1934 orang telah melayarinya
  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. ?>
复制代码


sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan