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 bre
In short
$csv = array_map('str_getcsv', file($file_path, FILE_SKIP_EMPTY_LINES));
Explanation
file
reads the content of the file into an array. TheFILE_SKIP_EMPTY_LINES
will skip the empty lines in the file.array_map
will apply the functionstr_getcsv
on each element of the array.str_getcsv
will parse the string input for fields incsv
format and return an array containing the fields.
Read more about str_getcsv
Read more about file
Read more about array_map
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;
}
}
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;