Hi I am writing a file import script for CSV files. I have an option where the user selects whether the file contains headers or not. In case the file does contain headers ($headers == 1), I want the script to skip the first line of the CSV file.

I was wondering what's the best way to do this, I came up with the following code which works, but I suspect there is a better way to do it:

							$no_of_clients = 0;
							$counter=0;
							while ( ($data = fgetcsv($handle, '', ',') ) !== FALSE ) {
								if  ( ($counter == 0) && ($headers == 1) ) { } 
								else {
									$business_name = trim($data[0]);
									$name = trim($data[1]);
									$surname = trim($data[2]);			
									$comments = trim($data[3]);
									$email = trim($data[4]);
									$telephone = trim($data[5]);				
									$address = trim($data[6]);
									$vatno = trim($data[7]);			
									$date_joined = trim($data[8]);			  
$active = trim($data[9]); $db->query("INSERT INTO clients (client_id, business_name, name, surname, comments, email, address, vatno, date_joined, active)". "VALUES (NULL, '$business_name', '$name', '$surname', '$comments', '$email', '$address', '$vatno',"."'$date_joined', '$active') "); $no_of_clients++; } $counter++; }

    Goodness gracious ... what are your tabs set at? 85?

      That's certainly one way of doing it, hard to say if there is a "better" way. Since you are reading line by line and not the entire file into a variable, you pretty much have to have the counter like you have. The only improvement I can see, other then the tabs 😉, is to build your if statement in such a way that you don't have an empty code block.

      if($headers == 1 && $counter != 0){
         //process logic
      }
      

      other methods I've seen are to read the complete file into a string, then using unset to get rid of the first entry. Something like...

      $data = file_get_contents($file_path);
      $lines = explode("\n", $data);
      
      if($headers){
         unset($data[0]);
      }
      
      foreach($lines as $line){
        //....
      }
      

        You don't really need a counter:

        if($headers == 1) {
           fgets($handle); // read and ignore the first line
        }
        while( ($data = fgetcsv($handle, '', ',') ) !== FALSE ) {
           // etc.
        }
        
          Write a Reply...