I'm new in PHP and I really need your help. I have a CSV-file (named *"Test.csv") in this form:
"ID";"Nom de famille";"Prénom";"Age";"Téléphone mobile";"Téléphone";"Téléphone 2";"Fax";"Adresse de messagerie";"Commentaires"
I need PHP code that can count how many lines in a specific CSV-file are and also store the "Age" field of each line in an array.
The most robust solution I can think of is just reading the file record by record because CSV data may contain newlines inside the values:
$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)
For Windows:
$count = substr_count(file_get_contents($filename), "
");
Nix:
$count = substr_count(file_get_contents($filename), "
");
You can find information about extracting a single field into an array from this post:
I'd keep it simple.
function age($line)
{
$cols = explode(",",$line);
return $cols[3];
}
$lines = explode("
",file_get_contents($filename));
$count = count($lines);
$ages = array_map("age",$lines);
$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.'
';
print_r($age_arr);
The file function is just for you.
This function reads an entire file into an array.
Here is the code you need:
<?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);
?>
Note: A Remote URL can be used as a filename with this function if the fopen wrappers have been enabled. But i hope you are gonna use a local file.
Happy PHP coding.