使用PHP,我创建了一个CSV文件数组,其中包含我想用此行下载的文件的URL:
$urls = explode(',',file_get_contents('urls.csv'));
Run Code Online (Sandbox Code Playgroud)
完成此操作后,我使用以下代码块.
foreach($urls as $url){
$fname = 'not important right now ;)'
$fcon = fopen($fname,'w');
fwrite($fcon,file_get_contents($url));
fclose($fcon);
}
Run Code Online (Sandbox Code Playgroud)
这很好用,它会下载文件中的所有文件!
但不幸的是,它没有我想要的那么高效.我想要2,3或4个同时下载来节省一些时间.我怎样才能做到这一点?
如果您有权访问,curl
可以使用curl_multi_exec.首先将您的$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";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1864 次 |
最近记录: |