This is the standard code on php.net:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>
";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />
";
}
}
fclose($handle);
}
?>
Let's assume that test.csv has 3 rows with:
cell11,cell12,cell13
cell21,cell22,cell23
cell31,cell32,cell33
Is it possible to use a foreach loop instead of the while used here and still get the values inside test.csv, for further use?
The code above gives this result:
3 fields in line 1:
cell11
cell12
cell13
3 fields in line 2:
cell21
cell22
cell23
3 fields in line 3:
cell31
cell32
cell33
This is what I have tried:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
// while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// $num = count($data);
// echo "<p> $num fields in line $row: <br /></p>
";
// $row++;
// for ($c=0; $c < $num; $c++) {
// echo $data[$c] . "<br />
";
// }
// }
foreach(($data = fgetcsv($handle, 1000, ",")) as $field){
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>
";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />
";
}
}
fclose($handle);
}
?>
And the result:
3 fields in line 1:
cell11
cell12
cell13
3 fields in line 2:
cell11
cell12
cell13
3 fields in line 3:
cell11
cell12
cell13