I have a CSV file that has three columns,
Name ID Date
and info below. Is it possible to have PHP read the file and put the columns into three arrays with the information?
Is there an easy system for this?
Cheers
Ryan
I have a CSV file that has three columns,
Name ID Date
and info below. Is it possible to have PHP read the file and put the columns into three arrays with the information?
Is there an easy system for this?
Cheers
Ryan
How about fgetscsv() ?
output.txt contents 3 columns separe by “|” like:
Pedro|1020|01/01/70
Pablo|1030|02/18/71
Simon|1040|10/09/60
Juan|1050|20/05/86
Judas|1060|22/02/67
Bartolome|1070|12/12/78
Santiago|1080|26/10/80
<?php
$file = ‘output.txt’;
$Name=array();
$ID=array();
$Date=array();
$lines = file($file);
foreach($lines as $line)
{
list( $Nametmp, $IDtmp, $Datetmp ) = split( ‘\|’, $line );
array_push($Name, $Nametmp);
array_push($ID, $IDtmp);
array_push($Date, $Datetmp);
}
foreach($Name as $indice => $valor)
print “$valor <br>”;
echo “…<BR>”;
foreach($ID as $indice => $valor)
print “$valor <br>”;
echo “…<BR>”;
foreach($Date as $indice => $valor)
print “$valor <br>”;
?>
I know this thread is over a week old, and the posts thus far happily answer the original query but I’d like to add my own two pennies into the pot in the form of another code snippet.
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
list($name, $id, $date) = $row;
// Do something with fields
}
Different field delimiters, separators and escape characters (defaults are double-quotes ("), comma (,) and backslash (\) respectively) can be specified using the SplFileObject::setCsvControl() method.
For example, to parse henry.ramgon’s pipe-delimited data you could use:
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl("|");
foreach ($file as $row) {
list($name, $id, $date) = $row;
// Do something with fields
}
The foreach can also be replaced by manually looping over the file to more closely resemble the procedural fopen/fgetcsv loop:
$file = new SplFileObject("data.csv");
while ($row = $file->fgetcsv()) {
list($name, $id, $date) = $row;
// Do something with fields
}
For more info on the SplFileObject class check out its PHP manual section.