hyperexpert
hyperexpert

Reputation: 532

fgetcsv skip blank lines in file

I have this script that I did, it basically grabs all the files in my "logs" folder and merge them all in one array file, my only problem is that, sometimes the script breaks if there is blank line or empty line! how can I tell it to automatically skip blank empty lines and go to next? blank lines are not necessarily at the top or bottom! could be in the middle of the csv file

<?php
    $csv = array();
    $files = glob('../logs/*.*');
    $out = fopen("newfile.txt", "w");

    foreach($files as $file){
        $in = fopen($file, "r");

    while (($result = fgetcsv($in)) !== false)

        {   
            $csv[] = $result;
        }

        fclose($in);
        fclose($out);
    }

    print json_encode(array('aaData' => $csv ));
?>

Upvotes: 15

Views: 25352

Answers (4)

A Friend
A Friend

Reputation: 1476

The currently accepted answer does not account for multiple columns, where an additional empty row would look more like ,,,,, instead of just being NULL.

To catch both empty single-column cases and multi-column empty cases, you can do the following:

while (($result = fgetcsv($in)) !== false) {
    if (empty(array_filter($result))) {
        continue; // Skip this iteration
    }
}

Using array_filter filters out all empty values, and then we check if that filtered array is empty (which would be the case if the the entire line is of empty values)

Upvotes: 0

ash__939
ash__939

Reputation: 1599

In short

$csv = array_map('str_getcsv', file($file_path, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES));

Explanation

  1. file reads the content of the file into an array. The FILE_SKIP_EMPTY_LINES will skip the empty lines in the file.
  2. array_map will apply the function str_getcsv on each element of the array. str_getcsv will parse the string input for fields in csv format and return an array containing the fields.

Read more about str_getcsv

Read more about file

Read more about array_map

Upvotes: 2

rubydio
rubydio

Reputation: 115

This works 100% tested, simplest way. The explanation is that blank lines make fgetcsv return a non-empty array with just a null element inside.

if ($result[0] == NULL)
    continue;

Upvotes: 6

Tomas Creemers
Tomas Creemers

Reputation: 2715

As you can read in the documentation for fgetcsv():

A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Checking for that before adding it to your data array should be sufficient:

while (($result = fgetcsv($in)) !== false) {
    if (array(null) !== $result) { // ignore blank lines
        $csv[] = $result;
    }
}

Upvotes: 23

Related Questions