Count rows in csv php

Php get row count of csv

How can I get the total number of rows in a csv file with PHP? If file is huge, better use this scheme, like is said in post: If you only want to count carriage returns (line breaks) try this: source: Count New Lines in Text File Solution 2: If your description entries are always enclosed in quotes: now sizeof($matches[1]) contains number of rows in csv Question: I make a php page in which i populate csv file to the checkbox,how i count number of rows of csv file. To get the actual number of lines I am currently using: I then do another loop to process the CSV. Is there a way to get the number of rows in a CSV without using the above while loop? CSV Here is a sample CSV.

PHP find count of csv file records

Hello I have written a code in php to read from a CSV file, print it and count the number of lines. Now I also need to find the number of records. Can someone help me out? Thank you!

Use fgetcsv() instead of fgets() . This will parse the row into fields and return an array. Then you can use count() to get the number of elements, and add this to a total.

 fclose($fp); echo "Total rows = $rows, total cells = $cells"; ?> 

How to get the row number of CSV, I think count($data[‘csvData’]) will return the no. of rows. – Kumar V. Mar 18, 2014 at 5:55.

How to count number of rows in CSV

I have a csv which includes a column allowing a multi-line string.

sku,name,description 123,"Product Name Here","Multi-line description goes here. Lots of multi-line content" 

I am interested in counting the number of rows I have in my CSV. I have tried

 $num_rows = count(file($filename)); var_dump($num_rows); //4 < WHAY too high 

but this counts each line in the multi-line cell as well.

To get the actual number of lines I am currently using:

//get number of rows $num_rows = 0; while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) < $num_rows++; >var_dump($num_rows); //2 < The actual number of rows 

I then do another while loop to process the CSV.

Is there a way to get the number of rows in a CSV without using the above while loop?

CSV

Here is a sample CSV. The number of lines I am looking for is 3 not 28

sku, name, description 123, "Product name", "

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Mauris pretium enim facilisis, tincidunt elit id, congue est.

Donec eu eros quis elit mattis dapibus.

Sed euismod augue nec metus accumsan, et ultricies elit mattis.

Vestibulum aliquet est sit amet neque congue lacinia.
Donec viverra augue quis orci interdum mattis.
Phasellus ullamcorper risus quis dolor tempus sagittis.

Integer vel augue iaculis turpis vestibulum commodo eu quis nunc.

" 456, "Another Product name", "

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Mauris pretium enim facilisis, tincidunt elit id, congue est.

Donec eu eros quis elit mattis dapibus.

Sed euismod augue nec metus accumsan, et ultricies elit mattis.

Vestibulum aliquet est sit amet neque congue lacinia.
Donec viverra augue quis orci interdum mattis.
Phasellus ullamcorper risus quis dolor tempus sagittis.

Integer vel augue iaculis turpis vestibulum commodo eu quis nunc.

"

In PHP5 you have a very fast solution for small-medium sized files:

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

source: How can I get the total number of rows in a csv file with PHP?

Читайте также:  Php get code from url

If file is huge, better use this scheme, like is said in post:

$c =0; $fp = fopen("test.csv","r"); if($fp) < while(!feof($fp))< $content = fgets($fp); if($content) $c++; >> fclose($fp); echo $c; 

If you only want to count carriage returns (line breaks) try this:

$count = substr_count(file_get_contents($filename), "\r\n"); 

source: Count New Lines in Text File

If your description entries are always enclosed in quotes:

$matches = array(); preg_match_all("/(description|\")$/m", file_get_contents($filename), $matches); 

now sizeof($matches[1]) contains number of rows in csv

Is it possible to count how many rows have an empty specified 'cell,

How to count number of rows in csv file using php? [duplicate]

I make a php page in which i populate csv file to the checkbox,how i count number of rows of csv file.

$file = $fu['filepath'].$fu['filename']; $handle=@fopen($file,"r"); if($handle) < while($row = fgetcsv($handle, 1024))< echo "".$row[0]." 
"; > > else < // File doesn't exist. do something. >
$file = $fu['filepath'].$fu['filename']; $fileData=@file($file,"r"); $noOfLines = count($fileData); if ($noOfLines > 0) < while ($row = fgetcsv($handle, 1024)) < echo "".$row[0]." 
"; > > else < // File doesn't exist. do something. >

PHP - Count Distinct Value in a CSV file, You could just read the file line by line instead of collecting all store IDs in an array and then doing an array_count_values() saving you an

Источник

How to count number of rows in CSV

but this counts each line in the multi-line cell as well. To get the actual number of lines I am currently using:

//get number of rows $num_rows = 0; while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) < $num_rows++; >var_dump($num_rows); //2 < The actual number of rows 

I then do another while loop to process the CSV. Is there a way to get the number of rows in a CSV without using the above while loop?

Читайте также:  Tera Byte Video Game Creation Camp

CSV

sku, name, description 123, "Product name", "

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Mauris pretium enim facilisis, tincidunt elit id, congue est.

Donec eu eros quis elit mattis dapibus.

Sed euismod augue nec metus accumsan, et ultricies elit mattis.

Vestibulum aliquet est sit amet neque congue lacinia.
Donec viverra augue quis orci interdum mattis.
Phasellus ullamcorper risus quis dolor tempus sagittis.

Integer vel augue iaculis turpis vestibulum commodo eu quis nunc.

" 456, "Another Product name", "

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Mauris pretium enim facilisis, tincidunt elit id, congue est.

Donec eu eros quis elit mattis dapibus.

Sed euismod augue nec metus accumsan, et ultricies elit mattis.

Vestibulum aliquet est sit amet neque congue lacinia.
Donec viverra augue quis orci interdum mattis.
Phasellus ullamcorper risus quis dolor tempus sagittis.

Integer vel augue iaculis turpis vestibulum commodo eu quis nunc.

"

Источник

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

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

if (($fp = fopen("test.csv", "r")) !== FALSE) < while (($record = fgetcsv($fp)) !== FALSE) < $row++; >echo $row; > 

This kind of solution should work, but the problem is the "while(record. ) bit, potentially; It breaks on empty lines. Note; none of the offered solutions that count lines in the file are reliable, as they are only counting the lines, not the csv entries (which can contain newline characters)

10 Answers 10

Create a new file reference using SplFileObject :

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

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.

Works with PHP >= 5.1 - and is memory efficient. Use $file->rewind() to go back to the start of the file.

@LeoCavalcante I ended up having to use this combination of flags to get it to work (on windows) $file->setFlags(SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);

Similar problem to the previous "solution" that loads up the whole file: you'll only count physical rows, and a csv file can easily contain newlines that are part of the content; so the result will be skewed.

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); 

This works for small file. If you have a huge CSV file (GB size), using file() to read the entire file and count() is probably a bad idea, because it stores the file in memory, and may hang a low memory system.

Читайте также:  Html entities что это

Just be aware that there is no easy way to do all this that would cover 100% of cases simple because the value of CSV column may contain new line character. This means that to get true number of 'records' in the file you would actually have to parse the file.

$c =0; $fp = fopen("test.csv","r"); if($fp) < while(!feof($fp))< $content = fgets($fp); if($content) $c++; >> fclose($fp); echo $c; 

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:

$rows = shell_exec('$(/bin/which cat) file.csv | $(/bin/which tr) "\r" "\n" | $(which wc) -l'); 

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

CSV rows are separated by line breaks. Therefore, split the rows by line breaks, and you will get an array of rows, which is countable.

if (($fp = fopen("test.csv", "r")) !== FALSE)

You're not actually reading from the file pointer. And if you're just counting lines, then count(file("test.csv")) would achieve it quicker. In some CSV variants however quoted values may enclose linebreaks.

Note; none of higher-upvoted solutions that count lines in the file are reliable, as they are only counting the lines, not the csv entries (which can contain newline characters)

I'm using a similar solution to op, and it works perfectly, but with op's code the while part can break on empty lines, which is potentially his problem.

So it looks like this (edited op's code)

$rowCount=0; if (($fp = fopen("test.csv", "r")) !== FALSE) < while(!feof($fp)) < $data = fgetcsv($fp , 0 , ',' , '"', '"' ); if(empty($data)) continue; //empty row $rowCount++; >fclose($fp); > echo $rowCount; 

Thanks, @Robbie Averill to be honest, I'm not sure if it would lead to the same result in all circumstances - most notably, empty lines. I've a feeling that the other answer would simply count empty lines, while this one definitely won't. Shame on me for skipping reviewing the negative-rated answers, it's indeed reasonably close.

I find this the most reliable:

$file = new SplFileObject('file.csv', 'r'); $file->setFlags( SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE ); $file->seek(PHP_INT_MAX); $lineCount = $file->key() + 1; 

I'd probably upvote this if there was an explanation. I have a policy against upvoting snippet dumps -- even if they are helpful/good.

Источник

Оцените статью