PHP 一直以来都是以页面级别的生存方式直接, 上一次请求和下一次的变量无法公用 (不像常驻内存语言)
- 所以
PHP
的绝大部分代码都是从上到下执行, 没有回调的功能 curl_multi_*
系列函数可以让PHP
过一把”多线程”的爽
官方并发请求 demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php require __DIR__ . '/../vendor/autoload.php'; use Curl\MultiCurl; $urls = array( 'tag3' => 'https://httpbin.org/post', 'tag4' => 'https://httpbin.org/get', 'tag5' => 'https://httpbin.org/html', ); $multi_curl = new MultiCurl(); $data = []; $multi_curl->success(function ($instance) { echo 'call to ' . $instance->id . ' with "' . $instance->myTag . '" was successful.' . "\n"; }); $multi_curl->error(function ($instance) { echo 'call to ' . $instance->id . ' with "' . $instance->myTag . '" was unsuccessful.' . "\n"; }); $multi_curl->complete(function ($instance) use (&$data) { echo 'call to ' . $instance->id . ' with "' . $instance->myTag . '" completed.' . "\n"; $data[] = $instance->tag; }); foreach ($urls as $tag => $url) { $instance = $multi_curl->addGet($url); $instance->myTag = $tag; } // wait all request completed $multi_curl->start(); // tag 的顺序并不是一定的, 取决于 http 请求哪个先返回 var_dump($data); |