Remove Blank lines in a Csv file

Asked

Viewed 782 times

3

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

For example

File . csv

"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.

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

I wrote this code but it’s not working someone can 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);
 }
  • Which error your code returns?

1 answer

2


Do it this way:

<?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 mistake you’re making is that on the line $lines = fgetcsv($or, 5000, ",",'"');, is reading a line only from the output.csv file, thus foreach is going through the items on that line, not every line in the archive.

  • I don’t understand, within the conditional, you’re turning the empty lines into array and counting the indices?

  • No, the lines where all items are formed by empty string are being reduced to an array with no item, so when the array is counted with Count is returned 0, that way this row is not inserted in the new csv file.

  • Quite simplistic. I was already thinking about using regex to make this kkk filter

  • 5* works perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.