使用php导入多个文件

时间:2015-08-10 07:32:29

标签: php mysql csv

我正在尝试在我的表中导入csv文件。在互联网上搜索,我找到了一个有效的代码,并根据我的需要进行了修改。

不幸的是,它仅适用于单个文件插入。我进一步尝试编辑它,但它只是插入目录中的最后一个文件。任何帮助将不胜感激。

//get the csv file
    $dir = "Files/";
    $currentFile = glob($dir."*.csv");
    $counter = count($currentFile);

        foreach ( $currentFile as $filename) {
            $handle = fopen($filename,"r");
        }

        $file = basename($filename);
        //loop through the csv file and insert into database 
    do { 

        if ($data[0]) { 
            mysql_query("INSERT INTO tblCoordinates (gps_id,lat,lng,time,cmt,cnt,cty,str,cde,lnt,hgt,name) VALUES 
                ( 
                    '$file',
                    '".mysql_real_escape_string($data[0])."',
                    '".mysql_real_escape_string($data[1])."',
                    '".mysql_real_escape_string($data[2])."',
                    '".mysql_real_escape_string($data[3])."',
                    '".mysql_real_escape_string($data[4])."',
                    '".mysql_real_escape_string($data[5])."',
                    '".mysql_real_escape_string($data[6])."',
                    '".mysql_real_escape_string($data[7])."',
                    '".mysql_real_escape_string($data[8])."',
                    '".mysql_real_escape_string($data[9])."',
                    '".mysql_real_escape_string($data[10])."'
                ) 
            "); 
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    //

$ counter表示我的$dir中有4个文件是真的,文件名是"5729.csv", "4563.csv", "8718.csv", "4494.csv"

我的问题:代码插入但只是最后一个文件" 4494.csv"。我怎么能插入所有文件?

2 个答案:

答案 0 :(得分:1)

您的foreach循环过早关闭

foreach ( $currentFile as $filename) {
    $handle = fopen($filename,"r");

    // process your files here

} // close 'foreach'

答案 1 :(得分:0)

扩展你的foreach。目前,您只在循环中分配$handle变量,但do循环不在foreach中,因此它只渲染最后一个文件。

foreach ($currentFile as $filename) {
    // Your loop only keeps setting the $handle
    $handle = fopen($filename,"r");
}

// At this point, only the last entry from $currentFile is parsed

所以它应该是这样的:

foreach ($currentFile as $filename) {
    $handle = fopen($filename,"r");

    $file = basename($filename);

    //loop through the csv file and insert into database 
    do { 
        // Your parse logic here...
    } while ($data = fgetcsv($handle,1000,",","'")); 
} // foreach ends here