tobeydw
tobeydw

Reputation: 107

How to remove empty lines from CSV file in PHP?

I have an issue with my output.csv file. This is what it looks like currently. I'm fine with either creating a new csv file that is modified or just modifying this csv file, but not sure how to go about it.

cn,mail,telephonenumber,uid
,,,
admin,,,
"Isaac Newton",[email protected],,newton
"Albert Einstein",[email protected],314-159-2653,einstein
"Nikola Tesla",[email protected],,tesla

I would like the output to be

cn,mail,telephonenumber,uid
admin,,,
"Isaac Newton",[email protected],,newton
"Albert Einstein",[email protected],314-159-2653,einstein
"Nikola Tesla",[email protected],,tesla

As you can see the second row is completely deleted. I've tried the following, but it doesn't work (this is from Remove Blank ROWS from CSV files in php)

$lines = file("output.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$num_rows = count($lines);
foreach ($lines as $line) {
    $csv = str_getcsv($line);
    if (count(array_filter($csv)) == 0) {
        $num_rows--;
    }
}

EDIT:

Here's my current PHP

            $filename = "output.csv";
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="' . $filename . '"');

            $file = fopen("ad.csv","r");

            while(! feof($file))
              {
              print_r(fgets($file));
              }
            fclose($file);

So essentially, I have a csv file named "ad.csv" that contains the information I need to be put into "output.csv". I was wondering how you would edit the output.csv such that it sends the download after being edited to remove the blank lines?

Currently, with Nigel's code attached to the bottom, it doesn't edit the outputted csv file.

Upvotes: 0

Views: 1367

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

If when you identify an empty row, you can then remove that row from the lines in the original array. Then just put all the remaining lines back together to the same file...

$lines = file("output.csv", FILE_SKIP_EMPTY_LINES );
$num_rows = count($lines);
foreach ($lines as $lineNo => $line) {
    $csv = str_getcsv($line);
    if (count(array_filter($csv)) == 0) {
        unset($lines[$lineNo]);
    }
}
file_put_contents("output.csv", $lines);

I've removed FILE_IGNORE_NEW_LINES so that the new lines are kept in the array.

Upvotes: 2

Related Questions