如何使用php从csv下载多个文件作为参考


How to download multiple files using php from csv as the references?

对PHP来说有点陌生,但我已经开始了解它了。

我想做什么…

我有一个csv,其中包含对文件的引用,我可以下载。

我发现这个页面:如何通过php下载xml文件?

这使我能够下载一个xml文件,如果我写url和目录,我想保存它没有问题。

我如何修改这个php获得所有xml文件在我的csv?

我认为它将是类似:foreach和变量函数等,但不知道如何。

同样在csv中只包含文件名而不包含完整的url,但url的第一部分将始终保持不变。下载目录也是如此。我希望所有的文件下载到相同的目录,我选择和文件名将是相同的我下载的。

如果我现在想下载图像或任何其他文件类型,我该如何更改php ?我想这应该很容易吧?

谢谢你的帮助约翰。

我假设CSV文件如下所示:

"Filename"URL"

"文件1";;

"文件2";;

"文件3";;

"文件4";;

URL到f4

"文件5";;URL到f5"

"文件6";;

列分隔符是;字符串分隔符是"

所以代码应该是这样的:
<?php
$fileContent = $file("path/to/csv/file"); // read the file to an array
array_shift( $fileContent ); // remove the first line, the header, from the array
foreach( $fileContent as $line ) {
    $columns = str_getcsv( $line, ";", '"' );
    $url = $columns[1]; // as suposed previously the url is in the second column
    $filename = $columns[0];
    downloadFile( $url, $filename );
}
function downloadFile( $url, $filename ) {
    $newfname = "/path/to/download/folder/" . $filename ;
    $file = fopen ($url, "rb");
    if ($file) {
        $newf = fopen ($newfname, "wb");
        if ($newf)
            while(!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
            }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}