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?
Here is a sample CSV. The number of lines I am looking for is 3
not 28
sku, name, description
123, "Product name", "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Mauris pretium enim facilisis, tincidunt elit id, congue est.</p>
<p>Donec eu eros quis elit mattis dapibus.</p>
<p>Sed euismod augue nec metus accumsan, et ultricies elit mattis.</p>
<p>Vestibulum aliquet est sit amet neque congue lacinia.<br/>
Donec viverra augue quis orci interdum mattis.<br/>
Phasellus ullamcorper risus quis dolor tempus sagittis.</p>
<p>Integer vel augue iaculis turpis vestibulum commodo eu quis nunc.</p>"
456, "Another Product name", "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Mauris pretium enim facilisis, tincidunt elit id, congue est.</p>
<p>Donec eu eros quis elit mattis dapibus.</p>
<p>Sed euismod augue nec metus accumsan, et ultricies elit mattis.</p>
<p>Vestibulum aliquet est sit amet neque congue lacinia.<br/>
Donec viverra augue quis orci interdum mattis.<br/>
Phasellus ullamcorper risus quis dolor tempus sagittis.</p>
<p>Integer vel augue iaculis turpis vestibulum commodo eu quis nunc.</p>"
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.