0

对 php 有点陌生,但我开始对它有所了解。

我想做的事...

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

我找到了这个页面:How to download xml file through in php?

如果我编写要保存的 url 和目录,这使我能够下载 xml 文件而没有问题。

如何修改此 php 以获取 csv 中的所有 xml 文件?

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

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

另外,如果我想现在下载图像或任何其他文件类型,我将如何更改 php?我认为这将相当容易?

感谢您的帮助约翰

4

1 回答 1

0

我会假设 CSV 文件如下所示:

“文件名”;“网址”

“文件 1”;“f1 的 URL”

“文件 2”;“f2 的 URL”

“文件 3”;“f3 的 URL”

“文件 4”;“f4 的 URL”

“文件 5”;“f5 的 URL”

“文件 6”;“f6 的 URL”

所以列分隔符是;和字符串分隔符"

所以代码会是这样的:

<?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);
    }
}
于 2013-04-01T12:47:05.070 回答