php中curl异步并发请求http的示例

小编给大家分享一下php中curl异步并发请求http的示例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

10年积累的成都网站设计、网站制作经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有大祥免费网站建设让你可以放心的选择与我们合作。

先来看下同步的代码以及请求时间。

$start_time=date("h:i:sa");
for ($i=0; $i <100 ; $i++) { 
	$urls[]="http://www.downxia.com/downinfo/2315".$i.".html";
	GetTitle(geturl("http://www.downxia.com/downinfo/2315".$i.".html"));
}
function geturl($url){
       
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
}
function GetTitle($output){

	preg_match('/.*<\/title>/i',$output,$matches);
	var_dump($matches[0]);
}
$end_time=date("h:i:sa");
echo '开始时间是:'.$start_time;
echo '结束时间是:'.$end_time;</pre><p><img src="/upload/otherpic69/2207.jpg" alt="php中curl异步并发请求http的示例"></p><p>最下面可以看到时间花了27秒。</p><p>接下来看下php curl 异步并发请求http的代码以及花费时间。</p><pre>$start_time=date("h:i:sa");

$urls=[];
for ($i=0; $i <100 ; $i++) { 
	$urls[]="http://www.downxia.com/downinfo/2315".$i.".html";
}
var_dump($urls);
// GetTitle('klasjdkla<title>313asds12');

rolling_curl($urls,'GetTitle');

function GetTitle($output){

	preg_match('/.*<\/title>/i',$output,$matches);
	var_dump($matches[0]);
}
$end_time=date("h:i:sa");

echo '开始时间是:'.$start_time;
echo '结束时间是:'.$end_time;

function rolling_curl($urls, $callback, $custom_options = null)
{//多个url访问

    // make sure the rolling window isn't greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

    $master   = curl_multi_init();
    $curl_arr = array();

    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }

    do {
        while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
        if ($execrun != CURLM_OK) {
            break;
        }

        // a request was just completed -- find out which one
        while ($done = curl_multi_info_read($master)) {
            $info = curl_getinfo($done['handle']);
            if ($info['http_code'] == 200) {
                $output = curl_multi_getcontent($done['handle']);

                // request successful.  process output using the callback function.
                $callback($output);

                // start a new request (it's important to do this before removing the old one)
                $ch                   = curl_init();
                $options[CURLOPT_URL] = $urls[$i++]; // increment i
                curl_setopt_array($ch, $options);
                curl_multi_add_handle($master, $ch);

                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done['handle']);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);

    curl_multi_close($master);
    return true;
}</pre><p><img src="/upload/otherpic69/2208.jpg" alt="php中curl异步并发请求http的示例"></p><p>才花了3秒?实际上我感觉应该是花了5秒,因为启动比同步要慢,开始的时候卡了2秒。</p><p>http请求效率,毋庸置疑是异步远远高于同步。</p><p>核心请求代码如下:(这是老外写的,有点小问题,最后的提示undefined offset)</p><pre>function rolling_curl($urls, $callback, $custom_options = null)
{//多个url访问

    // make sure the rolling window isn't greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

    $master   = curl_multi_init();
    $curl_arr = array();

    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }

    do {
        while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
        if ($execrun != CURLM_OK) {
            break;
        }

        // a request was just completed -- find out which one
        while ($done = curl_multi_info_read($master)) {
            $info = curl_getinfo($done['handle']);
            if ($info['http_code'] == 200) {
                $output = curl_multi_getcontent($done['handle']);

                // request successful.  process output using the callback function.
                $callback($output);

                // start a new request (it's important to do this before removing the old one)
                $ch                   = curl_init();
                $options[CURLOPT_URL] = $urls[$i++]; // increment i
                curl_setopt_array($ch, $options);
                curl_multi_add_handle($master, $ch);

                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done['handle']);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);

    curl_multi_close($master);
    return true;
}</pre><p>修改一下。只要在新增url的时候加个判断就好了。// 当$i等于$urls数组大小时不用再增加了。</p><pre>function rolling_curl($urls, $callback, $custom_options = null)
{//多个url访问

    // make sure the rolling window isn't greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

    $master   = curl_multi_init();
    $curl_arr = array();

    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }

    do {
        while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
        if ($execrun != CURLM_OK) {
            break;
        }

        // a request was just completed -- find out which one
        while ($done = curl_multi_info_read($master)) {
            $info = curl_getinfo($done['handle']);
            if ($info['http_code'] == 200) {
                $output = curl_multi_getcontent($done['handle']);

                // request successful.  process output using the callback function.
                $callback($output);

                // start a new request (it's important to do this before removing the old one)
                // 当$i等于$urls数组大小时不用再增加了
                if($i<sizeof($urls)){
                    $ch                   = curl_init();
                    $options[CURLOPT_URL] = $urls[$i++]; // increment i
                    curl_setopt_array($ch, $options);
                    curl_multi_add_handle($master, $ch);
                }
                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done['handle']);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);

    curl_multi_close($master);
    return true;
}</pre><p>以上是“php中curl异步并发请求http的示例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!</p>            
            
                        <br>
            当前标题:php中curl异步并发请求http的示例            <br>
            分享路径:<a href="http://www.frzxz.com/article/pdedjo.html">http://www.frzxz.com/article/pdedjo.html</a>
        </div>
    </div>
    <div class="other">
        <h3>其他资讯</h3>
        <ul>
            <li>
                    <a href="/article/dojep.html">CDN有用吗?企业建站用CDN加速有没有用?</a>
                </li><li>
                    <a href="/article/cgsip.html">企业应该如何选择适合自己的数据库?</a>
                </li><li>
                    <a href="/article/ipshh.html">7个致命的网站开发错误-创新互联</a>
                </li><li>
                    <a href="/article/hdsido.html">windows系统动态图的简单介绍</a>
                </li><li>
                    <a href="/article/heeoej.html">硬盘在windows系统的简单介绍</a>
                </li><li>
                    <a href="/article/dopcohg.html">wordpress待发布 wordpress今日发布</a>
                </li><li>
                    <a href="/article/dihedgh.html">深黑色android 深黑色血是月经怎么回事</a>
                </li><li>
                    <a href="/article/dghgpso.html">怎样对一个网站进行准确的定位</a>
                </li><li>
                    <a href="/article/cdjcish.html">soa架构是什么意思</a>
                </li><li>
                    <a href="/article/ccsedej.html">html如何用链接打开网站</a>
                </li>        </ul>
    </div>
</div>
<div class="footer">
    <div class="contain">
        <div class="foot-nav clearfix">
            <ul class="footer-menu">
                <li class="dropdown" ><a class="dropdown-toggle">服务范围<b class="caret"></b></a>
                    <ul class="child-menu">
                        <li><a href="/website.html">网站建设</a></li>
                        <li><a href="/weixin/" rel="nofollow">微信开发</a></li>
                        <li><a href="/app/" rel="nofollow">APP开发</a></li>
                        <li><a href="/design/" rel="nofollow">品牌设计</a></li>
                        <li><a href="/market/" rel="nofollow">营销推广</a></li>
                    </ul>
                </li>
                <li class="dropdown"><a href="/webcase/" class="dropdown-toggle" title="成都做网站案例">成都做网站案例<b class="caret"></b></a>
                    <ul class="child-menu">
                        <li><a href="/webcase/jtssgslist.html" id="ctl00_show_85" title="集团上市公司">集团上市公司</a></li>
                        <li><a href="/webcase/ppwzlist.html" id="ctl01_show_81" title="品牌网站">品牌网站</a></li>
                        <li><a href="/webcase/xiangyingshilist.html" id="ctl02_show_82" title="响应式网站">响应式网站</a></li>
                        <li><a href="/Marketingwebsite/index.html" id="ctl03_show_83" title="营销型网站">营销型网站</a></li>
                        <li><a href="/waimaowangzhan/index.html" id="ctl04_show_84" title="外贸网站">外贸网站</a></li>
                    </ul>
                </li>
                <li class="dropdown"><a href="/news/" class="dropdown-toggle">新闻中心 <b class="caret"></b></a>
                    <ul class="child-menu">
            <li><a href="/news/2.html" id="ctl00_show_70" title="网站建设">网站建设</a></li><li><a href="/news/3.html" id="ctl00_show_70" title="网站设计">网站设计</a></li><li><a href="/news/5.html" id="ctl00_show_70" title="网站制作">网站制作</a></li><li><a href="/news/6.html" id="ctl00_show_70" title="网站优化">网站优化</a></li>          </ul>
                </li>
                <li class="dropdown"><a href="/Knowledge/" class="dropdown-toggle">知识学堂 <b class="caret"></b></a>
                    <ul class="child-menu">
            <li><a href="/websitelist/8.html" title="网站建设知识">网站建设知识</a></li><li><a href="/websitelist/9.html" title="网站设计知识">网站设计知识</a></li><li><a href="/websitelist/10.html" title="微信营销知识">微信营销知识</a></li><li><a href="/websitelist/11.html" title="营销推广知识">营销推广知识</a></li>          </ul>
                </li>
                <li class="dropdown"><a href="/about/" class="dropdown-toggle" rel="nofollow">关于我们 <b class="caret"></b></a>
                    <ul class="child-menu">
                        <li><a href="/about/jj/index.html" id="ctl00_show_1300" title="公司简介" rel="nofollow">公司简介</a></li>
                        <li><a href="/about/history/index.html" id="ctl01_show_1301" title="发展历史" rel="nofollow">发展历史</a></li>
                        <li><a href="/about/jjtd/index.html" id="ctl02_show_1302" title="精英团队" rel="nofollow">精英团队</a></li>
                        <li><a href="/about/join/" rel="nofollow">加入我们</a></li>
                        <li><a href="/about/contact/" rel="nofollow">联系暖宝</a></li>
                    </ul>
                </li>
            </ul>
            <dl class="last-dl">
                <dt> <a href="javascript:;" title="联系我们" rel="nofollow">联系暖宝</a> </dt>
                <dd class="conta"> <span><img src="/Public/Home/images/zg_ewm.png" width="100" /><br />
          企业微信号</span> </dd>
            </dl>
        </div>
        <div class="childcompan clearfix"> </div>
        <div class="copy">
            友情链接:
            <a href="http://www.cdbrznjsb.com/" title="成都网站开发" target="_blank">成都网站开发</a>   <a href="http://www.dasuibian.com/" title="成都柴油发电机出租" target="_blank">成都柴油发电机出租</a>   <a href="http://www.kmlktfg.com/" title="昆明窗帘定制" target="_blank">昆明窗帘定制</a>   <a href="http://www.hongcaicy.cn/" title="餐饮管理公司" target="_blank">餐饮管理公司</a>   <a href="http://www.kmhgg.com/" title="成都汽车改装" target="_blank">成都汽车改装</a>   <a href="http://www.scemts.cn/" title="德阳东方电机技改" target="_blank">德阳东方电机技改</a>   <a href="http://www.tkbvh.com/" title="运动护具销售" target="_blank">运动护具销售</a>   <a href="http://www.yaancyfdj.cn/" title="雅安柴油发电机出租" target="_blank">雅安柴油发电机出租</a>   <a href="http://www.fenxiangzhe.com/" title="fenxiangzhe.com" target="_blank">fenxiangzhe.com</a>   <a href="http://www.bjzptech.com/" title="湖北劳保用品" target="_blank">湖北劳保用品</a>           </div>
        <br>
        <a href="http://www.frzxz.com/">成都网站制作</a><strong> <a href="/">成都网站建设</a></strong>,成都定制网站建设——全心全意建网站公司 </div>
</div>
<script type="text/javascript" src="/Public/Home/js/meiqia.js"></script>
<script type="text/javascript" src="/Public/Home/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/Public/Home/js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="/Public/Home/js/i.js"></script>
<script type="text/javascript" src="/Public/Home/js/script.js"></script>
<script type="text/javascript" src="/Public/Home/js/SuperSlide.js"></script>
<script type="text/javascript" src="/Public/Home/js/jquery.toTop.min.js"></script>
<script type="text/javascript" src="/Public/Home/js/num-change.js"></script>
<script type="text/javascript" src="/Public/Home/js/jquery.nicescroll.min.js"></script>
<script type="text/javascript">
    $(".menu li").eq(7).addClass("current-menu-item");
</script>
</body>
</html>
<script>
    $(".con img").each(function(){
        var src = $(this).attr("src");    //获取图片地址
        var str=new RegExp("http");
        var result=str.test(src);
        if(result==false){
            var url = "https://www.cdcxhl.com"+src;    //绝对路径
            $(this).attr("src",url);
        }
    });
    window.onload=function(){
        document.oncontextmenu=function(){
            return false;
        }
    }
</script>