在CSV导入中跳过第0行

时间:2013-06-28 00:22:20

标签: php mysql csv upload

所以我将CSV文件上传到我的mysql数据库,我希望它总是跳过第0行,其中第0行是列名

我使用的当前代码

    //connect to the database 
    $connect = mysql_connect("localhost","username","password"); 
    mysql_select_db("mydatabase",$connect); //select the table 
    // 

    if ($_FILES[csv][size] > 0) { 

        //get the csv file 
        $file = $_FILES[csv][tmp_name]; 
        $handle = fopen($file,"r"); 

        //loop through the csv file and insert into database 
        do { 
            if ($data[0]) { 
                mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES 
                    ( 
                        '".addslashes($data[0])."', 
                        '".addslashes($data[1])."', 
                        '".addslashes($data[2])."' 
                    ) 
                "); 
            } 
        } while ($data = fgetcsv($handle,1000,",","'")); 
        // 

        //redirect 
        header('Location: import.php?success=1'); die; 

} 

我需要删除以下行 来源,名字,姓氏,电话1,电话2,联系电子邮件,标题,参考号码,日期,状态

我打算做一个if($data[0]=="Source")然而问题是如果他们改变了CSV文件的布局或其他什么。

所以我的问题很简单,我们可以跳过第一行是第0行吗?

但如果第一行不是第0行,我可以收到提醒,这样我就可以查看CSV文件了吗?

3 个答案:

答案 0 :(得分:1)

您可能有兴趣尝试使用LOAD DATA INFILE

LOAD DATA INFILE '/path/to/your/file.csv' 
INTO TABLE contacts 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

答案 1 :(得分:0)

读取文件的第一行并丢弃它,如果它是标题行:

    $file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file,"r"); 

    // read the first line
    $data = fgetcsv($handle,1000,",","'")
    // if the first line is a header, discard it and read the next
    if ($data[0] == "Source:") {
       $data = fgetcsv($handle,1000,",","'")
    }

    //loop through the csv file and insert into database 
    do { 
        if ($data[0]) { 
            mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES 
                ( 
                    '".addslashes($data[0])."', 
                    '".addslashes($data[1])."', 
                    '".addslashes($data[2])."' 
                ) 
            "); 
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    // 

顺便提一下,你的do...while循环就像你最初拥有它一样。在阅读之前,您正在查看数据。通过预读,我已经添加它应该可以工作。

答案 2 :(得分:0)

fopen之后,我会调用fgets($handle);并忽略返回值,从而跳过第一行。