The example in this article describes the method of using foreach combined with curl to achieve multi-threading in PHP. Share it with everyone for your reference, the details are as follows:
Multi-threading is not supported by PHP, but we can use foreach to pseudo-multi-thread, but this pseudo-multi-threading is not necessarily faster than single-threading. Specifically, Let’s look at an example.
When using the foreach statement to loop through image URLs and save all images locally through CURL, a problem arises that only one can be collected. Now we will combine foreach and CURL to make multiple URL requests. Summary below.
Method 1: Loop request
$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.'##:'.$data.'<br>'; } curl_close($ch);
What needs special attention in the above code is that curl_close must be placed outside the end of the foreach loop. If it is placed inside, the problem I mentioned above will appear. Multiple IMGURLs can only collect one URL.
Method 2: Multi-threaded loop
<?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( 'http://www.php.cn', 'http://tools.php.cn', ));
Here we mainly use curl_multi_init() to implement multiple url requests, but because PHP itself does not support multi-threading , so the speed of pseudo-multithreading is not necessarily faster than that of single-threading.
I hope this article will be helpful to everyone in PHP programming.
For more analysis on the method of foreach combined with curl to achieve multi-threading in PHP, please pay attention to the PHP Chinese website!