This article mainly introduces the method of implementing multi-threading by combining foreach with curl in php, and analyzes the principle and implementation skills of simulating multithreading by combining foreach statements with curl loop calls, for more information about how to use foreach in php and curl to implement multithreading, see the example in this article. We will share this with you for your reference. The details are as follows:
Multithreading is not supported by php, but we can use foreach to pseudo-multithreading. However, the speed of this pseudo-multithreading is not necessarily the same as that of a single thread. here is an example.
When the foreach statement is used to loop the image URL and save all the images locally through CURL, one problem occurs, now we will summarize the methods of combining foreach and CURL for multi-URL requests.
Method 1: cyclic requests
$ Sr = array (url_1, url_2, url_3); foreach ($ sr as $ k => $ v) {$ curlPost = $ v .'? F = input parameter '; $ ch = curl_init ($ curlPost); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true); // get data and return curl_setopt ($ ch, CURLOPT_BINARYTRANSFER, true ); // when CURLOPT_RETURNTRANSFER is enabled, $ data = curl_exec ($ ch); echo $ k is returned. '##:'. $ data.'
';} Curl_close ($ ch );
The above code requires special attention that curl_close must be placed outside the end of the foreach loop. if it is placed inside, multiple imgurls mentioned above will appear, only one URL can be collected.
Method 2: multi-thread loop
$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( 'https://www.php1.cn', 'http://tools.php1.cn',));
Curl_multi_init () is mainly used to implement requests with multiple URLs. However, php does not support multithreading itself, so the speed of pseudo-multithreading is not necessarily faster than that of a single thread.
I hope this article will help you with PHP programming.
For more information about how to use foreach in php and curl to implement multithreading, see The PHP Chinese website!