Reputation: 203
i'm using the code below to show a csv file as html table with php. My issue is how to show only specific columns of the csv file. For example I'd show the columns number 1,5,9,15. How can be modified the code to select that specific fields?
Thanks in advance, Mattew
<?php
$row = 1;
if (($handle = fopen("donors.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<td style="border-top: 1px solid rgb(111,180,224); border-left: 1px solid rgb(111,180,224); border-bottom: 1px solid rgb(111,180,224);" align="left" bgcolor="#0066cc" height="36" valign="middle" ><b><font color="#ffffff" size="2"> '.$value.' </font></b></td>';
}else{
echo '<td style=" border-bottom: 1px solid rgb(111,180,224);" sdval="9" sdnum="1040;" align="left" bgcolor="#ffffff" height="25" valign="middle"><font color="#000000" size="2"> '.$value.' </font></td>';
}
}
if ($row == 1) {
echo '</tr>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
echo '</center>';
fclose($handle);
}
?>
Upvotes: 1
Views: 9678
Reputation: 6625
turn your CSV string into an array:
$data_as_array = explode(',',$data_as_csv);
echo "This is the value in column #2: ".$data_as_array[1];
This solution doesn't consider yet the number of rows, this post does (see accepted answer):
How to create an array from a CSV file using PHP and the fgetcsv function
Upvotes: 0
Reputation: 3649
// before your while loop
$wantedColumns = array(1,5,9,15);
// ...
for ($c=0; $c < $num; $c++) {
if (!in_array($c,$wantedColumns)) continue;
// ....
Upvotes: 1