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;
}
count(file('filename.csv', FILE_SKIP_EMPTY_LINES));
I know this is an old post, but I've been googling this issue, and found that the only problem with the original code was that you need to define
$row
outside the while loop, like this:Just in case it helps someone :) echo $row; }
Create a new file reference using
SplFileObject
:Try to
seek
to the highest Int PHP can handle: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:
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.
Here's another option using
file()
to read the entire file into an array, automatically parsing new lines etc:Also, since PHP5, you can pass in the
FILE_SKIP_EMPTY_LINES
... to skip empty lines, if you want to:Manual: http://php.net/manual/en/function.file.php
I know that this is pretty old, but actually I ran into the same question. As a solution I would assume to use linux specific logic:
NOTE: this only works for linux only and this only should be used if you are 100% certain that your file has no multiline-cells