how to leave out blank rows using fgetcsv

Chiko picture Chiko · Aug 16, 2011 · Viewed 8.3k times · Source

I have been working on importing a csv file into a mysql database. Problem is my client gets the files already with some bad formatting. the rows end at 43 but the file goes down to 65078!!

When importing, the script takes forever. What can I do to make sure just the rows from 0 to 44 get imported? Here's the code i'm using.

  <table>
<?php
//fgetcsv($handle, 1024, delimiter)
$file = fopen("prices.csv", "r");
$row = 0;

    while($csv_line = fgetcsv($file,1024)) {

      if($row ==    4){
        echo "How many headers do we have: ".count($csv_line)."<tr>";

         foreach($csv_line as $header){

           if($header !== NULL){
            print "<td>$header</td>";
           }
         }
         echo "</tr>";
      } 

      if($row > 6) {

        echo '<tr>';

        for ($i = 0, $j = count($csv_line); $i < $j; $i++) {

          echo '<td>'.$csv_line[$i].'</td>';

        }

        echo "</tr>\n";

      } else {

        $row++;

      }

    } 
?>

</table>

Answer

leticia picture leticia · Aug 16, 2011

If the number of filled rows isn't fixed, you can use similar approach with:

if (empty($line)) { break; }

Your comment give me an idea for a better solution:

Here http://php.net/manual/en/function.fgetcsv.php appears this "A blank line in a CSV file will be returned as an array comprising a single null field" so maybe this helps:

while(($csv_line = fgetcsv($file,1024)) && $csv_line[0]) {

Will read only until finds an empty row.