我有一个csv,其中包含一个允许多行字符串的列。
sku,name,description
123,"Product Name Here","Multi-line description
goes here.
Lots of multi-line content"
我有兴趣计算我的CSV中的行数。我试过了
$num_rows = count(file($filename));
var_dump($num_rows); //4 < WHAY too high
但这也计算了多行单元格中的每一行。
获取我当前使用的实际行数:
//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
然后我再做一个while
循环来处理CSV。
有没有办法在不使用上述while循环的情况下获取CSV中的行数?
以下是CSV示例。我要查找的行数是3
而不是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>"
答案 0 :(得分:0)
在PHP5中,您可以快速解决中小型文件:
$fp = count(file('test.csv', FILE_SKIP_EMPTY_LINES));
来源:How can I get the total number of rows in a CSV file with PHP?
如果文件很大,最好使用这个方案,就像帖子中所说的那样:
$c =0;
$fp = fopen("test.csv","r");
if($fp){
while(!feof($fp)){
$content = fgets($fp);
if($content) $c++;
}
}
fclose($fp);
echo $c;
如果您只想计算回车(换行符),请尝试:
$count = substr_count(file_get_contents($filename), "\r\n");
答案 1 :(得分:0)
如果您的描述条目始终用引号括起来:
$matches = array();
preg_match_all("/(description|\")$/m", file_get_contents($filename), $matches);
now sizeof($ matches [1])包含CSV中的行数