PHP 一直以来都是以页面级别的生存方式直接, 上一次请求和下一次的变量无法公用 (不像常驻内存语言)
- 所以
PHP
的绝大部分代码都是从上到下执行, 没有回调的功能 curl_multi_*
系列函数可以让PHP
过一把”多线程”的爽- 使用此库方便进行操作https://github.com/php-curl-class/php-curl-class
官方并发请求 demo
<?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);