Fgetcsv skips empty lines in a file

I have this script that I made, it basically captures all the files in my "logs" folder and merges them all into one array file, my only problem is that sometimes the script breaks if there are no empty lines or empty lines! How can I say that it automatically skips empty blank lines and moves on to the next? empty lines are not necessarily at the top or bottom! may 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 )); ?> 
+6
source share
2 answers

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

An empty string in the CSV file will be returned as an array containing one empty field and will not be considered an error.

Checking this before adding it to the data array should be sufficient:

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

This works in a 100% proven, easiest way. The explanation is that empty strings force fgetcsv to return a non-empty array with a null element inside.

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

Source: https://habr.com/ru/post/952069/


All Articles