Remove Blank Lines in a Csv File

3

I have the following csv file and would like to remove the lines that are blank

For example

.csv file

"C","C","X","123","asdsd","'232","'323","","323","23","4","dsa","dsad","dsa","ds","dsad","sdad,","24","0","11","4,2","fdf","","k","502","00","0035"," RAL","dgdf","R","12345","098765","321324",""
"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
"C","C","X","123","asdsd","'232","'323","","323","23","4","dsa","dsad","dsa","ds","dsad","sdad,","24","0","11","4,2","fdf","","k","502","00","0035"," GL","dgdf","R","12345","098765","321324",""
"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
"C","C","X","123","asdsd","'232","'323","","323","23","4","dsa","dsad","dsa","ds","dsad","sdad,","24","0","11","4,2","fdf","","k","502","00","0035"," G","dgdf","R","12345","098765","321324",""
"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
"C","C","X","123","asdsd","'232","'323","","323","23","4","dsa","dsad","dsa","ds","dsad","sdad,","24","0","11","4,2","fdf","","k","502","00","0035"," ERL","dgdf","R","12345","098765","321324",""
"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""

And I wanted to remove the blank lines ie.

"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""

I wrote this code but it is not working, can someone help me?

     $or = fopen("output.csv", 'r'); 
     $nv = fopen("novo.csv", 'a+'); 
     $lines = fgetcsv($or, 5000, ",",'"');
     foreach ($lines as $line) {
         $csv = str_getcsv($line);
          if (count(array_filter($csv)) != 0) {
             fputcsv($nv, $line ,",",'"');
         }
     }
     fclose($or);
     fclose($nv);
 }
    
asked by anonymous 27.11.2015 / 14:01

1 answer

2

Do as follows:

<?php

$or = fopen("output.csv", 'r');
$nv = fopen("novo.csv", 'a+');

while (($line = fgetcsv($or, 5000)) !== false) {

  if (count(array_filter($line)) > 0) {
    fputcsv($nv, $line);
  }

}

fclose($or);
fclose($nv);

The error you are making is that in the $lines = fgetcsv($or, 5000, ",",'"'); line, you are reading a line only from the output.csv file, so foreach is traversing the items in that line, not each line in the file. >     

27.11.2015 / 14:50