PHP fgetcsv count lines end of file, eof

PHP fgetcsv count lines

Due to fgetcsv read only a line from open file, or line by line if looping. As decribe below, it doesn’t able to return number of line from specific file.

  • The fgetcsv() function parses a line from an open file, checking for CSV fields.
  • The fgetcsv() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.
  • This function returns the CSV fields in an array on success, or FALSE on failure and EOF.

Solution below may help to detect enf of file:

$this->file = fopen($this->path,"r");
if(!$this->file)
{
	echo "Error opening data file.\n";
	exit;
}
$row = 0;
while ( ! feof($this->file) )
{
	$data = fgetcsv($this->file, '', ",");
	
	if(feof($this->file))
	{
		//if end of file do somethine
	}
	
	if( !empty($data) )
	{
		//if not enf of file, process data
	}
	$row++;
}

fclose($this->file);

By Keenlio, November 17, 2014

What do you think?

Leave a Reply

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


+ seven = 9

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>