Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the total number of rows in a CSV file with PHP?

Tags:

php

csv

count

row

How can I get the total number of rows that are in a CSV file using PHP? I'm using this method but can get it to work properly.

if (($fp = fopen("test.csv", "r")) !== FALSE) {    while (($record = fgetcsv($fp)) !== FALSE) {       $row++;   }    echo $row; } 
like image 251
telexper Avatar asked Jan 30 '14 03:01

telexper


People also ask

How do I find out how many rows a CSV file has?

Using len() function Under this method, we need to read the CSV file using pandas library and then use the len() function with the imported CSV file, which will return an int value of a number of lines/rows present in the CSV file.

How can I get the number of columns in a CSV file in PHP?

If I understand, you simply need count($line) , because fgetcsv() has returned an array representing one row from the CSV file. The array's count() is therefore the number of source columns.


2 Answers

Create a new file reference using SplFileObject:

$file = new SplFileObject('test.csv', 'r'); 

Try to seek to the highest Int PHP can handle:

$file->seek(PHP_INT_MAX); 

Then actually it will seek to the highest line it could in the file, there is your last line and the last line + 1 is equals to your total lines:

echo $file->key() + 1; 

Tricky, but this will avoid you from loading the file contents into memory, which is a very cool thing to do when dealing with really large files.

like image 125
Leo Cavalcante Avatar answered Oct 17 '22 03:10

Leo Cavalcante


Here's another option using file() to read the entire file into an array, automatically parsing new lines etc:

$fp = file('test.csv'); echo count($fp); 

Also, since PHP5, you can pass in the FILE_SKIP_EMPTY_LINES... to skip empty lines, if you want to:

$fp = file('test.csv', FILE_SKIP_EMPTY_LINES); 

Manual: http://php.net/manual/en/function.file.php

like image 27
scrowler Avatar answered Oct 17 '22 05:10

scrowler