PHP 批量 GET 请求并按顺序返回内容
下面是一个简单的 PHP 函数,可以实现多个 URL 的 GET 请求,并将返回的内容按顺序排列后返回:
function multi_get($urls) {
$result = array();
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
$ch[$i] = curl_init($url);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $ch[$i]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running > 0);
foreach ($ch as $i => $url) {
$result[$i] = curl_multi_getcontent($ch[$i]);
curl_multi_remove_handle($mh, $ch[$i]);
}
curl_multi_close($mh);
return $result;
}
使用方法:
$urls = array(
'http://example.com/page1',
'http://example.com/page2',
'http://example.com/page3',
);
$result = multi_get($urls);
// $result 数组中包含了按顺序排列的三个页面的返回内容
原文地址: https://www.cveoy.top/t/topic/muTC 著作权归作者所有。请勿转载和采集!