Example of multi-thread implementation of foreach curl in php

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.