dqask02082 2013-04-01 10:29
浏览 68
已采纳

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

kind of new to php but am starting to get my head around it a little.

What i want to do...

I have a csv which contains references to files that i can download.

I found this page: How to download xml file through in php?

This enabled me to download an xml file if i write the url and directory i want to save it to with no problems.

How to i modify this php to get all xml files in my csv?

I assume it will be something like: foreach and variable functions etc but have no idea how.

Also in the csv contains only the file name not the full url, but the first part of the url will always stay the same. And same goes for the download directory. I want all the files to be downloaded into the same directory as i pick and the file name will be the same as the one im downloading.

Also how would i change the php if for example i want to now download images, or any other file type? I assume this will be fairly easy?

Thanks for your help John

  • 写回答

1条回答 默认 最新

  • doudouwd2017 2013-04-01 12:47
    关注

    I will suppose that the CSV file is like the following:

    "Filename";"URL"

    "File 1"; "URL to f1"

    "File 2"; "URL to f2"

    "File 3"; "URL to f3"

    "File 4"; "URL to f4"

    "File 5"; "URL to f5"

    "File 6"; "URL to f6"

    So the column separator would be ; and the string separator "

    so the code would be something like:

    <?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);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)