计算PHP文件中有多少行


Count how many lines there are in a file with PHP

我是PHP新手,我真的需要你的帮助。我有一个csv文件(名为*"Test.csv")在这个形式:

"ID";"Nom de famille";"Prénom";"Age";"Téléphone mobile";"Téléphone";"Téléphone 2";"Fax";"Adresse de messagerie";"Commentaires"

我需要PHP代码,可以计算有多少行在一个特定的csv文件,也存储"年龄"字段的每行在一个数组。

我能想到的最可靠的解决方案是逐个记录读取文件,因为CSV数据可能在值中包含换行符:

$ages = array(); $records = 0;
$f = fopen('data.csv', 'rt');
while (($row = fgetcsv($f, 4096, ';')) !== false) {
    // skip first record and empty ones
    if ($records > 0 && isset($row[3])) {
        $ages[] = $row[3]; // age is in fourth column
    }
    ++$records;
}
fclose($f);
// * $ages contains an array of all ages
// * $records contains the number of csv data records in the file 
//   which is not necessarily the same as lines
// * count($ages) contains the number of non-empty records)

文件函数就是为你准备的。

这个函数将整个文件读入数组。

下面是你需要的代码:

<?php
$ageArray = array();
$inputFile = 'filename.csv';
$lines = file($inputFile); 
echo count($lines);
// count($lines) will give you total number of lines
// Loop through our array
foreach ($lines as $line_num => $line) {
    $ageArray[] = $line[3]; //'Age';
}
//Here is the o/p
print_r($ageArray);
?>

注意:如果fopen包装器已经启用,远程URL可以用作此功能的文件名。但是我希望你使用本地文件。

Windows:

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

Nix:

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

你可以从这篇文章中找到关于将单个字段提取到数组中的信息:

将CSV列放入数组

$fname='1.csv';
$line_cnt=0;
$age_arr=array();
if($fh=fopen($fname,'r'))
{
  while(!feof($fh))
  {
     $str=fgets($fh);
     if($str!='')
     {
        $line_cnt++;
        $a=explode(';',$str);
        $age_arr[]=$a[3];
     }
  }
  fclose($fh);
}
echo 'line_cnt='.$line_cnt.''n';
print_r($age_arr);

我会保持简单。

function age($line)
{
    $cols = explode(",",$line);
    return $cols[3];
}
$lines = explode("'n",file_get_contents($filename));
$count = count($lines);
$ages = array_map("age",$lines);