1

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.

0

5 Answers 5

5

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)
Sign up to request clarification or add additional context in comments.

10 Comments

tanks @Jack how can i get the file from an Upload-File Form and put instead of 'data.csv'
i get the file only for reading the content but not storing it
@user1989195 the code works for an arbitrary file name, so an uploaded file should require no additional workarounds. On how you should handle files uploads I would kindly ask you to read the manual on "handling file uploads"
which section in the page do you mean ?
SPL File object with CSV flag set is by definition more robust. The boilerplate code to open the file and to read it has been created already, so all you need to do is use new, call a method and foreach.
|
2

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.

3 Comments

Tannks a lot @OMG , how can i get the file from an Upload-File Form and put instead of 'data.csv'
Is there no way of just reading the file contents without saving it to the server?
i get the file from an Upload-File Form
0

For Windows:

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

Nix:

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

You can find information about extracting a single field into an array from this post:

putting csv column into an array

3 Comments

That's what PHP_EOL is for
Theoretically a CSV file might contain empty lines, especially if prepared in Excel
Is there no way of just reading the file contents without saving it to the server?
0
$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);

Comments

0

I'd keep it simple.

function age($line)
{
    $cols = explode(",",$line);
    return $cols[3];
}

$lines = explode("\n",file_get_contents($filename));
$count = count($lines);
$ages = array_map("age",$lines);

7 Comments

Is there no way of just reading the file contents without saving it to the server?
where does the file come from?
i get the file from an Upload-File Form
The file goes to a temp file. PHP will delete it when it's done unless you copy it somewhere. It has to be saved to disk. That's how PHP gets file uploads via a form. This is done by the web server before it calls PHP to handle the request.
so there is no solution exept copy the file and then delete it i after i done from using it?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.