Skip first line of fgetcsv method

后端 未结 6 595
长发绾君心
长发绾君心 2020-11-28 12:25

I have a CSV file and I read data from CSV file then I want to skip first line of CSV file.Which\'ll contain any header. I am using this code.

while (($emapDa         


        
相关标签:
6条回答
  • 2020-11-28 13:05

    You should use the fseek() method in order to get the desired line, regardless the current pointer position.

    At this example, get the first line after the loop:

    $file = fopen($path, "r");    
    
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
      // ...
    }
    
    fseek($file, 1, SEEK_CUR);
    

    You can use the third parameter to position the pointer in the file, as is:

    SEEK_SET – It moves file pointer position to the beginning of the file.

    SEEK_CUR – It moves file pointer position to given location.

    SEEK_END – It moves file pointer position to the end of file.

    0 讨论(0)
  • 2020-11-28 13:07

    Before beginning the while loop, just get the first line and do nothing with it. This way the logic to test if it's the first line is not needed.

    fgetcsv($file, 10000, ",");
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
      //....
    }
    
    0 讨论(0)
  • 2020-11-28 13:16

    A bit late, but here is another way to do so (without having to count all the lines): with fgets

    $file = fopen($filename, 'r');  // create handler
    fgets($file);  // read one line for nothing (skip header)
    while (($line = fgetcsv($file, 10000, ",")) !== FALSE) {
        // do your thing
    }
    

    One might consider this to be more elegant

    0 讨论(0)
  • 2020-11-28 13:28

    You can add a simple check and skip the query if the check fails:

    $firstline = true;
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
    {
        if (!$firstline) {
            // Code to insert into database
        }
        $firstline = false;
    }
    
    0 讨论(0)
  • 2020-11-28 13:29

    Try this simple code.

    $file = fopen('example.csv', 'r');  // Here example is a CSV name
    $row = 1;
    while (($line = fgetcsv($file, 10000, ",")) !== FALSE) {
    // $line is an array of the csv elements
    if($row == 1){ $row++; continue; }   // continue is used for skip row 1
    // print_r($line);
    // rest of your code
    }
    
    0 讨论(0)
  • 2020-11-28 13:32

    try:

    $flag = true;
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
       if($flag) { $flag = false; continue; }
       // rest of your code
    }
    
    0 讨论(0)
提交回复
热议问题