Home  >  Article  >  Backend Development  >  php 中curl 循环往请求多个URL和多线程去请求多个URL的方法

php 中curl 循环往请求多个URL和多线程去请求多个URL的方法

WBOY
WBOYOriginal
2016-06-13 12:57:58937browse

php 中curl 循环去请求多个URL和多线程去请求多个URL的方法

第一种:循环请求
$sr=array(url_1,url_2,url_3);
foreach ($sr as $k=>$v) {
	$curlPost=$v.'?f=传入参数';
	$ch = curl_init($curlPost) ; 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回   
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回   
	$data = curl_exec($ch) ;
	echo $k.'##:'.$data.'<br>';
}
curl_close($ch);

 

第二种 多线程请求

$sr=array(url_1,url_2,url_3);

$mh = curl_multi_init();
     foreach ($sr as $i => $url) {
      $curlPost=$url.'?f=%2Fpipefile%2Fskincss%2Fskincss_1356490012_1.zip%40%2Fskincss%2Fimages%2Fskincss_1356490012_1.jpg';
      $conn[$i]=curl_init($curlPost);
      curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);
      curl_multi_add_handle ($mh,$conn[$i]);
     } 
     do {
      $mrc = curl_multi_exec($mh,$active);
     } while ($mrc == CURLM_CALL_MULTI_PERFORM);
     while ($active and $mrc == CURLM_OK) {
      if (curl_multi_select($mh) != -1) {
       do {
        $mrc = curl_multi_exec($mh, $active);
       } while ($mrc == CURLM_CALL_MULTI_PERFORM);
      }
     } 
     foreach ($sr as $i => $url) {
      $res[$i]=curl_multi_getcontent($conn[$i]);
      curl_close($conn[$i]);
     }
  var_dump($res);

简单测试 后 发现,同时请求4个不同的URl,循环的处理速度 好像比多线程的快,这个问题有待验证


 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn