Php 如何计算CSV中的行数

Php 如何计算CSV中的行数,php,csv,Php,Csv,我有一个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

我有一个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

在PHP5中,您有一个非常快速的中小型文件解决方案:

$fp = count(file('test.csv', FILE_SKIP_EMPTY_LINES));
资料来源:

如果文件很大,最好使用这个方案,就像在帖子中说的:

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

来源:

如果您的描述条目总是用引号括起来:

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

现在sizeof($matches[1])包含CSV中的行数

$rows=count(explode(\r\n),file\u get\u contents('myCSVfile.CSV')?@sandnig希望换行符永远不会出现,\r\n,)不,没有任何快捷方式,while循环是唯一会返回正确结果的方法result@sandnig这不是也会有同样的问题吗,计算单元格中不应该计算的换行符?我认为
fgetcsv()
方法是一种方法,因为在这里解析时,您只需要了解csv格式。所有其他方法都要复杂得多,因为您必须实现这些知识。这并不能解决此处提到的问题:csv单元格中不应计数的换行符您好,我认为如果您使用“;”作为行分隔符(并对注释字段进行编码),会更容易。然后这将完成作业$count=substr\u count(file\u get\u contents($filename),“;”);仍然不允许出现
在数据中,你可以发布一个链接到csv文件的真实示例吗?海报在他们的问题中给出了一个csv文件的示例
$count = substr_count(file_get_contents($filename), "\r\n");
$matches = array();
preg_match_all("/(description|\")$/m", file_get_contents($filename), $matches);