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://bzwzjz.com/article/pdedjo.html">http://bzwzjz.com/article/pdedjo.html</a>
        </div>
    </div>
    <div class="other">
        <h3>其他资讯</h3>
        <ul>
            <li>
                    <a href="/article/dcseceo.html">腾讯云香港服务器换linux 腾讯云服务器 linux</a>
                </li><li>
                    <a href="/article/dcsedps.html">老域名购买地址怎么写好 老域名购买地址怎么写好看</a>
                </li><li>
                    <a href="/article/dcseccd.html">linux命令到桌面 linux常用命令桌面</a>
                </li><li>
                    <a href="/article/dcseccp.html">php怎么向数据库存数据 php怎么使用数据库</a>
                </li><li>
                    <a href="/article/dcsecoi.html">安卓调用阿里云上的服务器 android studio连接阿里云数据库</a>
                </li>        </ul>
    </div>
</div>
<div class="footer2">
    Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号 <br />友情链接:
    <a href="https://www.cdxwcx.com/wangzhan/mobile.html" target="_blank">手机网站建设 </a><a href="http://m.cdcxhl.com/liucheng.html" target="_blank">成都网站建设流程 </a><a href="http://chengdu.kswsj.cn/" target="_blank">高端网站设计 </a><a href="http://www.cxhljz.cn/" target="_blank">成都网站建设 </a><a href="http://www.cxjianzhan.com/" target="_blank">成都网站建设公司 </a><a href="http://m.cdxwcx.com/" target="_blank">成都网站建设 </a><a href="http://www.cqcxhl.com/" target="_blank">重庆企业网站建设 </a><a href="https://www.cdcxhl.com/xiangyingshi.html" target="_blank">响应式网站设计 </a><a href="http://www.cxhljz.cn/" target="_blank">成都网站建设公司 </a><a href="http://www.cdweb.net/" target="_blank">成都网站设计 </a><a href="http://www.4006tel.net/vision/website.html" target="_blank">网站设计 </a><a href="http://www.cdxwcx.cn/" target="_blank">成都网站设计 </a><a href="http://www.cdxwcx.cn/bj/" target="_blank">网站制作报价 </a><a href="https://www.cdcxhl.com/city/chengdu.html" target="_blank">四川成都网站建设 </a><a href="http://chengdu.cdcxhl.cn/jianshe/" target="_blank">成都网站建设公司 </a><a href="http://www.cdkjz.cn/fangan/led/" target="_blank">LED网站设计方案 </a><a href="https://www.cdcxhl.com/h5.html" target="_blank">成都h5网站建设 </a><a href="http://www.kswcd.com/solution/" target="_blank">网站建设方案 </a><a href="http://www.cxhljz.cn/" target="_blank">成都网站设计 </a><a href="https://www.cdcxhl.com/waimao.html" target="_blank">外贸营销网站建设 </a><a href="http://www.cdxwcx.cn/sheji/" target="_blank">网站设计公司 </a><a href="http://m.cdcxhl.cn/mobile/" target="_blank">网站建设公司 </a></div>

</body>
</html>
<script src="/Public/Home/js/wow.min.js"></script>
<script>
    if (!(/msie [6|7|8|9]/i.test(navigator.userAgent))) {
        new WOW().init();
    };
</script>
<div class="sidebar">
    <ul>
        <li><a href="http://wpa.qq.com/msgrd?v=3&uin=244261566&site=www.bzwzjz.com&menu=yes" target="_blank"><img src="/Public/Home/images/right_qq.png" /></a></li>
        <li><a href="http://wpa.qq.com/msgrd?v=3&uin=1683211881&site=www.bzwzjz.com&menu=yes" target="_blank"><img src="/Public/Home/images/qq.png" /></a></li>
        <li class="tel"><a href="tel:028-86922220"><img src="/Public/Home/images/right_tel.png" /></a></li>
        <div class="wx">
            <span class="weixin"><img src="/Public/Home/images/weixin.jpg"><br> 微信扫一扫在线咨询</span>
        </div>
        <li><a class="fx" href="#hero"><img src="/Public/Home/images/right_up.png" /></a></li>
    </ul>
</div>
<script type="text/javascript">
    $(function () {
        $('.sidebar .fx').click(function () {
            $('html,body').animate({
                scrollTop: '0px'
            }, 800);
        });
    });
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#fancybox-manual-b").click(function () {
            $.fancybox.open({
                href: 'map.html',
                type: 'iframe',
                padding: 5
            });
        })
    });
</script>
<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>