Reputation: 41
I have an csv file with rows and columns and I want to display column C and E. My result is always coming with everything like that: aaabbbcccddee
. Any idea how to do it separate like aaa bbb ccc dd ee
and showing only C column and E column?
Here's what I have so far:
$row = 1;
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Upvotes: 0
Views: 3408
Reputation: 6297
Only print the columns you want
$row = 1;
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo 'Data is ' . $data[2] . ' ' . $data[4]
}
fclose($handle);
}
The fgetcsv() function allows you to specify a delimiter, which in the above example is a comma (","). You can specify other delimiters, for example tabs ("\t").
Inside the while loop, the fgetcsv() command will return an array of values read from your line.
Therefore if your line is
111,aaa,bbb,ccc
Then $data will be
Array (
[0] => 111,
[1] => aaa,
[2] => bbb,
[3] => ccc,
)
Upvotes: 1