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://dcwzsj.com/article/dddeoc.html">http://dcwzsj.com/article/dddeoc.html</a>
        </div>
    </div>
    <div class="other">
        <h3>其他资讯</h3>
        <ul>
            <li>
                    <a href="/article/dgchjos.html">怎么链接别人的mysql 怎么连接别人的热点数据</a>
                </li><li>
                    <a href="/article/dgchjds.html">html5加阴影 html5设置文字阴影代码</a>
                </li><li>
                    <a href="/article/dgchgpi.html">html5载入音乐 html5怎么加音乐</a>
                </li><li>
                    <a href="/article/dgchghs.html">jquery定义对象 jquery定义json对象</a>
                </li><li>
                    <a href="/article/dgchgip.html">怎么创建MySQL的表 怎么创建mysql表格</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.cdxwcx.cn/sheji/" title="成都网站设计" target="_blank">成都网站设计</a>   <a href="http://www.chdeyu.com/" title="营山产后修复" target="_blank">营山产后修复</a>   <a href="http://www.nzanhua.com/" title="四川雕琢时光" target="_blank">四川雕琢时光</a>   <a href="http://m.xwcx.net/" title="自适应网站" target="_blank">自适应网站</a>   <a href="http://www.cdkjz.cn/" title="成都网站制作" target="_blank">成都网站制作</a>   <a href="https://www.cdcxhl.com/idc/zongshu.html" title="成都棕数机房" target="_blank">成都棕数机房</a>   <a href="http://www.scyarui.cn/" title="青羊区雕琢时光" target="_blank">青羊区雕琢时光</a>   <a href="http://www.cdhuace.com/zhuangxiu.html" title="成都铺面装修" target="_blank">成都铺面装修</a>   <a href="http://www.cdwuji.com/" title="正泰动物制药" target="_blank">正泰动物制药</a>   <a href="http://www.huilanmu.com/" title="边坡防护网" target="_blank">边坡防护网</a>           </div>
        <br>
        123ABC<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>