如何下载目录中的多个文件?

时间:2013-10-31 14:20:58

标签: php wget

我有一个在线目录中存在的文件名列表。下载所有内容的最佳方式是什么?例如,我想获得以下文件:

516d0f278f14d6a2fd2d99d326bed18b.jpg
b09de91688d13a1c45dda8756dadc8e6.jpg
366f737007417ea3aaafc5826aefe490.jpg

来自以下目录:

http://media.shopatron.com/media/mfg/10079/product_image/

也许是这样的:

$var = filelist.txt
for ( $i in $var ) {
    wget http://media.shopatron.com/media/mfg/10079/product_image/$i
}

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

$list = file_get_contents('path/to/filelist.txt');
$files = explode("\n", $list); ## Explode around new-line.
foreach ($files as $file) {
   file_put_contents('new_filename.jpg', file_get_contents('http://url/to/file/' . $file));
}

基本上,您会在新行周围展开列表以获取每一行,然后在服务器从您从中获取文件的任何地方下载file_put_contents文件。

答案 1 :(得分:0)

$files = file('filelist.txt');  //this will load all lines in the file into an array            
$dest = '/tmp/';  //your destination dir
$url_base = 'http://media.shopatron.com/media/mfg/10079/product_image/';

foreach($files as $f) {
   file_put_contents($dest.$f, file_get_contents($url_base.$f));
}

非常不言自明,但有一点:如果你不确定filelist.txt的内容,你应该清理文件名。

答案 2 :(得分:0)

这是我在等待答案时想出的。

<?php
$handle = @fopen("inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        exec("wget http://media.shopatron.com/media/mfg/10079/product_image/$buffer");
        echo "File ( $buffer) downloaded!<br>";
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

我通过修改PHP fgets man page中的示例来实现此目的。我还设置max_execution_time = 0(无限制)。

如果有人能证明他们的方法更有效率,我很乐意将他们的答案标记为已被接受。谢谢大家的答案!

相关问题