search
Homephp教程php手册php中foreach curl实现多线程例子

多线程是php不支持的但我们可以通过foreach来伪多线程了,但这个伪多线程速度不一定比单线程要单到哪里去了,具体来看个例子。

在利用foreach语句循环图片URL,并通过CURL将所有图片进行本地保存的函数时 ,出现了只能采集到一个的问题。现将foreach和CURL结合进行多URL请求的方法进行下总如。

方法1:循环请求

$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.&#39;##:&#39;.$data.&#39;<br>&#39;;
}
curl_close($ch);

上面代码需要特别注意的是,curl_close 一定要放在foreach循环结束的外面,如果放在里面的话,就会出现我上面提到的多个IMGURL ,只能采集到一个URL的问题。

方法2:多线程循环

<?php
multi_threads_request($nodes){
$mh = curl_multi_init();
$curl_array = array();
foreach($nodes as $i => $url)
{
$curl_array[$i] = curl_init($url);
curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $curl_array[$i]);
}
$running = NULL;
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while($running > 0);
$res = array();
foreach($nodes as $i => $url)
{
$res[$url] = curl_multi_getcontent($curl_array[$i]);
}
foreach($nodes as $i => $url){
curl_multi_remove_handle($mh, $curl_array[$i]);
}
curl_multi_close($mh);
return $res;
}
print_r(multi_threads_request(array(
    &#39;http://www.phprm.com&#39;,
    &#39;http://qq.phprm.com&#39;,
));

这里主要利用curl_multi_init()实现多个url 的请求,不过由于php自身并不支持多线程。所以伪多线程速度也不见得会比单线程快。


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool