When the foreach statement is used to loop the image URL and save all images locally through CURL, only one collection problem occurs. The following describes how to combine foreach and CURL for multiple 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 is returned.
$ Data = curl_exec ($ ch );
Echo $ k. '##:'. $ 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
<? 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.111cn.net ',
'Http: // qq.111cn.net ',
));
Curl_multi_init () is used to implement multiple url requests. However, php does not support multithreading. Therefore, the speed of pseudo-multithreading is not necessarily faster than that of a single thread.