在PHP中同时下载文件列表
发布时间:2020-12-13 17:30:50 所属栏目:PHP教程 来源:网络整理
导读:使用 PHP,我创建了一个CSV文件数组,其中包含我想用此行下载的文件的URL: $urls = explode(',',file_get_contents('urls.csv')); 完成此操作后,我使用以下代码块. foreach($urls as $url){ $fname = 'not important right now ;)' $fcon = fopen($fname,'w')
使用
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,你可以使用
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 $in"; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |