In php, foreach is combined with curl to implement multi-thread analysis. foreachcurl
This example describes how to use foreach in php to implement multithreading with curl. 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. '<br>';} 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
<?phpmulti_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.bkjia.com', 'http://tools.jb51.net',));
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.