Home > Article > Backend Development > Example analysis of foreach combined with curl to achieve multi-threading in PHP
This article mainly introduces the method of foreach combined with curl to realize multi-threading in PHP. It analyzes the principles and implementation techniques of foreach statement combined with curl loop call to simulate multi-threading in the form of examples. Friends in need can refer to it
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. Let’s take a look at an example.
When using the foreach statement to loop through image URLs and save all images locally through CURL, there is a problem that only one can be collected. Now we will summarize the method of combining foreach and CURL to make multiple URL requests.
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 in foreach If placed outside the end of the loop, there will be multiple IMGURLs as I mentioned above, and only one URL can be collected.
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.jb51.net', 'http://tools.jb51.net', ));
Here mainly uses curl_multi_init() to implement multiple URL requests. However, since PHP itself does not support multi-threading, the pseudo-multi-threading speed is It may not be faster than a single thread.
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning.
Related recommendations:
phpRead the server-side file and display it on the web page example
Use php to interact with the server and web front-end interface
Use php to realize the automatic login storage mechanism within a week
The above is the detailed content of Example analysis of foreach combined with curl to achieve multi-threading in PHP. For more information, please follow other related articles on the PHP Chinese website!