135-1821-9792

php中curl异步并发请求http的示例-创新互联

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

目前创新互联公司已为上千家的企业提供了网站建设、域名、网页空间、网站运营、企业网站设计、揭东网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

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

$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/otherpic41/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/otherpic41/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://kswsj.com/article/dddeoc.html">http://kswsj.com/article/dddeoc.html</a>
        </div>
    </div>
    <div class="other">
        <h3>其他资讯</h3>
        <ul>
            <li>
                    <a href="/article/pohhce.html">vue如何设置样式</a>
                </li><li>
                    <a href="/article/pohhsd.html">DNA存储,拯救人类数据危机的良方?</a>
                </li><li>
                    <a href="/article/pohphj.html">怎么给KVM设置Linux虚拟网络</a>
                </li><li>
                    <a href="/article/pohhss.html">PHP如何将秒数转成格式为天时分秒</a>
                </li><li>
                    <a href="/article/pohhsi.html">IOS如何实现应用内支付返回新旧Receipt适配</a>
                </li>        </ul>
    </div>
</div>
<!-- end #bd -->
<div class="c"></div>
<!-- begin #fd -->
<div id="fd" class="index-fd pr">
    <div class="map-bg3"></div>
    <div class="wp">
        <div class="fd-top">
            <dl>
                <dt>关于我们</dt>
                <dd>
                    <ul class="ul-fd">
                        <li><a href="http://www.kswsj.com/about#whous">我们是谁</a></li>
                        <li><a href="http://www.kswsj.com/about#ourcus">我们服务的客户</a></li>
                        <li><a href="http://www.kswsj.com/about#ourteam">我们的团队</a></li>
                    </ul>
                </dd>
            </dl>
            <dl>
                <dt>我们的服务</dt>
                <dd>
                    <ul class="ul-fd">
                        <li><a href="http://www.kswsj.com/service#webbuit">网站建设</a></li>
                        <li><a href="http://www.kswsj.com/service#weiweb">H5响应式 交互网站</a></li>
                        <li><a href="http://www.kswsj.com/service#webmobel">移动端 & 微网站定制</a></li>
                        <li><a href="http://www.kswsj.com/service#servweb">服务流程</a></li>
                        <li><a href="http://www.kswsj.com/service#solution">行业解决方案</a></li>
                    </ul>
                </dd>
            </dl>
            <dl>
                <dt>网站建设案例</dt>
                <dd>
                    <ul class="ul-fd">

                        <li><a href="http://www.kswsj.com/case/">公司集团</a></li>

                        <li><a href="http://www.kswsj.com/case/">数码电子科技</a></li>

                        <li><a href="http://www.kswsj.com/case/">建筑与设计</a></li>

                        <li><a href="http://www.kswsj.com/case/">安防门禁</a></li>

                        <li><a href="http://www.kswsj.com/case/">管理咨询美容</a></li>

                        <li><a href="http://www.kswsj.com/case/">外贸行业</a></li>

                    </ul>
                </dd>
            </dl>
            <dl>
                <dt>新闻动态</dt>
                <dd>
                    <ul class="ul-fd">

                        <li><a href="/news/2.html">成都网站建设</a></li><li><a href="/news/3.html">成都网站制作</a></li><li><a href="/news/4.html">成都网站设计</a></li>
                    </ul>
                </dd>
            </dl>
            <dl>
                <dt>联系我们</dt>
                <dd class="pr">
                    <p><a href="http://www.kswsj.com/news/" class="weixin"></a><a href="http://www.kswsj.com/news/" class="sina"></a><span class="weixin-pic"><img src="/Public/Home/pic/ewm.jpg"></span></p>
                    <p><b class="tel">135-1821-9792</b></p>
                    <h5>公司服务热线</h5>
                </dd>
            </dl>
        </div>
        <div class="link">
            友情链接:
            <a href="https://www.cdcxhl.com/" title="成都网站建设" target="_blank">成都网站建设</a>   <a href="http://www.bzwzjz.com/" title="专业网站建设" target="_blank">专业网站建设</a>   <a href="http://www.shufengxianlan.com/" title="艾名斯线缆" target="_blank">艾名斯线缆</a>   <a href="http://www.scjiangyou.cn/" title="scjiangyou.cn" target="_blank">scjiangyou.cn</a>   <a href="http://www.huineicun.com/" title="广安园林绿化公司" target="_blank">广安园林绿化公司</a>   <a href="http://www.cdfuwuqi.com/host/mianbeian/" title="免备案虚拟主机" target="_blank">免备案虚拟主机</a>   <a href="https://www.cdxwcx.com/jifang/guanghua.html" title="成都光华机房" target="_blank">成都光华机房</a>   <a href="http://www.cdxwcx.cn/tuoguan/deyang.html" title="德阳电信机房" target="_blank">德阳电信机房</a>   <a href="http://www.cdkjz.cn/develop/" title="网上商城开发" target="_blank">网上商城开发</a>   <a href="http://www.dmvi.cn/" title="成都广告公司" target="_blank">成都广告公司</a>           </div>
    </div>
    <div class="fd-copy">
        <div class="wp">
            <p><span style="color:#CCCCCC;">Copyright © 2009-2022 www.kswsj.com 成都快上网科技有限公司 版权所有</span> <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow" style="color:#CCCCCC;">蜀ICP备19037934号</a></p>
        </div>
    </div>
</div>
<div class="side">
    <ul>
        <li><a href="http://wpa.qq.com/msgrd?v=3&uin=631063699&site=qq&menu=yes" target="_blank">
            <div class="sidebox"><img src="/Public/Home/pic/side_icon02.png">在线咨询</div>
        </a></li>
        <li><a href="http://wpa.qq.com/msgrd?v=3&uin=631063699&site=qq&menu=yes" target="_blank">
            <div class="sidebox"><img src="/Public/Home/pic/side_icon01.png">在线咨询</div>
        </a></li>
        <li><a href="tel:135-1821-9792">
            <div class="sidebox"><img src="/Public/Home/pic/side_icon03.png"><span style="font-size:14px">135-1821-9792</span></div>
        </a></li>
    </ul>
</div>
<div class="side2">
    <ul>
        <li><a href="http://www.kswsj.com/news/"><img src="/Public/Home/pic/r_icon1.png" alt="成都网站建设"></a>
            <div class="weixin"><em></em><img src="/Public/Home/pic/ewm.jpg" alt="成都网站建设"></div>
        </li>
        <li><a href="javascript:goTop();" class="sidetop"><img src="/Public/Home/pic/r_icon2.png"></a></li>
    </ul>
</div>
<div class="fot">
    <ul>
        <li>
            <a href="https://p.qiao.baidu.com/cps/mobileChat?siteId=11284691&userId=6256368&type=1&reqParam=%20{%22from%22:0,%22sessionid%22:%22%22,%22siteId%22:%2211284691%22,%22tid%22:%22-1%22,%22userId%22:%226256368%22,%22ttype%22:1,%22siteConfig%22:%20{%22eid%22:%226256368%22,%22queuing%22:%22%22,%22siteToken%22:%226ce441ff9e2d6bedbdfc2a4138de449e%22,%22userId%22:%226256368%22,%22isGray%22:%22false%22,%22wsUrl%22:%22wss://p.qiao.baidu.com/cps3/websocket%22,%22likeVersion%22:%22generic%22,%22siteId%22:%2211284691%22,%22online%22:%22true%22,%22webRoot%22:%22//p.qiao.baidu.com/cps3/%22,%22bid%22:%22160142915792139572%22,%22isSmallFlow%22:0,%22isPreonline%22:0,%22invited%22:0%20},%22config%22:%20{%22themeColor%22:%224d74fa%22%20}%20}&appId=&referer=&iswechat=0&expectWaiter=-1&openid=null&otherParam=null&telephone=null&speedLogId=null&eid=null&siteToken=6ce441ff9e2d6bedbdfc2a4138de449e" target="_blank">
                <img src="/Public/Home/pic/fot1.png" alt="">
                <p>在线咨询</p>
            </a>
        </li>
        <li>
            <a href="tel:18980820575" target="_blank">
                <img src="/Public/Home/pic/fot2.png" alt="">
                <p>拨打电话</p>
            </a>
        </li>
    </ul>
</div>
<script type="text/javascript" src="/Public/Home/pic/jquery.js"></script>
<script type="text/javascript" src="/Public/Home/pic/lib.js"></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>