php – Why does fgetcsv() apparently sometimes treat "end of file" as an error?-ThrowExceptions

Exception or error:

From the manual at https://www.php.net/fgetcsv :

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Am I to interpret this as meaning that “end of file” is considered an error?!

I’ve been using fgetcsv() for a long time and never encountered that it returned FALSE on the last line, but recently, I encountered a CSV file where this happens. Very strange, especially considering the fact that I auto-convert the linebreaks to “standard” Unix ones before my operations with fgetcsv().

Am I not reading/understanding the manual correctly or what?

How to solve:

It just means that when there’s an error, or the end of the file is reached, it will return FALSE. Whether that last state is considered an “error”, or not, doesn’t seem relevant to me.

Answer´╝Ü

No. You have misunderstood the interpretation.
fgetcsv() returns “null” if the csv file was not opened by fopen() before loading with fgetcsv.
FALSE returns for other errors and when the end of the file is reached.
Therefore, a “while” cycle is used to read a file like this:

$file = fopen("myFile.csv", "a");

while(($row = fgetcsv($file, 1000, ",") !== FALSE) {

 /* now the $row variable is an array where line by line is stored from 
    $file. Here while-loop will read line by line from a file until it 
    reaches FALSE as the end of the file. 
 */
}

Leave a Reply

Your email address will not be published. Required fields are marked *