使用 PHP,我创建了一个 CSV 文件数组,其中包含我要使用以下行下载的文件的 URL:
$urls = explode(',',file_get_contents('urls.csv'));
完成此操作后,我使用以下代码块。
foreach($urls as $url){
$fname = 'not important right now ;)'
$fcon = fopen($fname,'w');
fwrite($fcon,file_get_contents($url));
fclose($fcon);
}
这很好用,它会下载文件中的所有文件!
但不幸的是,它没有我想要的那么有效。我想要同时进行 2,3 或 4 个下载,以节省一些时间。我怎样才能做到这一点?
如果您有权访问curl
您可以使用卷曲多重执行。首先分块你的$urls
将数组分成要同时执行的组数,然后使用curl_multi_exec
.
$all_urls = ['http://www.google.com',
'http://www.yahoo.com',
'http://www.bing.com',
'http://www.twitter.com',
'http://www.wikipedia.org',
'http://www.stackoverflow.com'];
$chunked_urls = array_chunk($all_urls,3); //chunk into groups of 3
foreach($chunked_urls as $i => $urls) {
$handles = [];
$mh = curl_multi_init();
foreach($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
// execute all queries simultaneously, and continue when all are complete
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
foreach($handles as $handle) {
file_put_contents("/tmp/output",curl_multi_getcontent($handle),FILE_APPEND);
curl_multi_remove_handle($mh, $handle);
}
curl_multi_close($mh);
print "Finished chunk $i\n";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)