pamo18 /
ramverk1-weather
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Pamo\MultiCurl; |
||
| 4 | |||
| 5 | /** |
||
| 6 | * Multi curl |
||
| 7 | */ |
||
| 8 | class MultiCurl |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * Multi curl |
||
| 12 | * |
||
| 13 | * @param array $url list to curl. |
||
| 14 | * |
||
| 15 | * @return array |
||
| 16 | */ |
||
| 17 | 2 | public function get(array $urls) : array |
|
| 18 | { |
||
| 19 | 2 | $id = 1; |
|
| 20 | 2 | $data = []; |
|
| 21 | $headers = [ |
||
| 22 | 2 | "Content-Type: application/json", |
|
| 23 | "charset=utf-8" |
||
| 24 | ]; |
||
| 25 | |||
| 26 | //create the multiple cURL handle |
||
| 27 | 2 | $curlHandler = curl_multi_init(); |
|
| 28 | |||
| 29 | 2 | foreach ($urls as $url) { |
|
| 30 | // create cURL resources |
||
| 31 | 2 | ${"ch$id"} = curl_init($url); |
|
| 32 | |||
| 33 | // set URL and other appropriate options |
||
| 34 | 2 | curl_setopt(${"ch$id"}, CURLOPT_RETURNTRANSFER, true); |
|
| 35 | 2 | curl_setopt(${"ch$id"}, CURLOPT_HTTPHEADER, $headers); |
|
| 36 | |||
| 37 | //add the handle |
||
| 38 | 2 | curl_multi_add_handle($curlHandler, ${"ch$id"}); |
|
| 39 | |||
| 40 | 2 | $id++; |
|
| 41 | } |
||
| 42 | |||
| 43 | //execute the multi handle |
||
| 44 | 2 | $running = null; |
|
| 45 | do { |
||
| 46 | 2 | curl_multi_exec($curlHandler, $running); |
|
| 47 | 2 | } while ($running); |
|
| 48 | |||
| 49 | 2 | $id = 1; |
|
| 50 | |||
| 51 | 2 | foreach ($urls as $url) { |
|
| 52 | //close the handle |
||
| 53 | 2 | curl_multi_remove_handle($curlHandler, ${"ch$id"}); |
|
| 54 | 2 | $contents = json_decode(curl_multi_getcontent(${"ch$id"}), JSON_UNESCAPED_UNICODE |true); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 55 | 2 | $data[] = $contents; |
|
| 56 | 2 | $id++; |
|
| 57 | } |
||
| 58 | |||
| 59 | 2 | curl_multi_close($curlHandler); |
|
| 60 | |||
| 61 | 2 | return $data; |
|
| 62 | } |
||
| 63 | } |
||
| 64 |