Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Blank ROWS from CSV files in php

Is it possible to remove all blank ROWS from a CSV file?

I'm trying to count all rows from a CSV file but would like to exclude lines that doesn't contain a value on a specific column or the whole row.

This is what I'm using to count the rows as of the moment.

$import = file($target_path, FILE_SKIP_EMPTY_LINES);
$num_rows = count($import);
echo $num_rows;

sample:

Jun,Bronse,137 Raven,Princeton,TX,75407,2147088671,[email protected],1990,CHEVROLET,K1500,,
,,,,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,,,,
Nella,Brown,111 Venna St,Princeton,TX,75407,2147177671,[email protected],1993,CHEVROLET,K1500,,
Jun,Bronse,137 Raven,Princeton,TX,75407,2147088671,[email protected],1990,CHEVROLET,K1500,,
,,,,,,,,,,,,
Jun,Bronse,137 Raven,Princeton,TX,75407,2147088671,[email protected],1990,CHEVROLET,K1500,,
like image 516
telexper Avatar asked Oct 16 '25 14:10

telexper


2 Answers

$lines = file("test.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$num_rows = count($lines);
foreach ($lines as $line) {
    $csv = str_getcsv($line);
    if (empty($csv[SPECIFIC_COLUMN])) {
        $num_rows--;
    }
}

If you don't want to check a specific column, but just filter out rows where all columns are empty, change it to:

    if (count(array_filter($csv)) == 0) {
like image 142
Barmar Avatar answered Oct 18 '25 06:10

Barmar


For empty rows:

$lines = file("test.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$num_rows = count($lines);
foreach ($lines as $line) {
    $csv = str_getcsv($line);
    if (!array_filter($csv)) {
        $num_rows--;
    }
}
like image 22
sjagr Avatar answered Oct 18 '25 07:10

sjagr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!