1

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 = "&nbsp;";
        }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">&nbsp;&nbsp;'.$value.'&nbsp;&nbsp;</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">&nbsp;&nbsp;'.$value.'&nbsp;&nbsp;</font></td>';
        }
    }

    if ($row == 1) {
        echo '</tr>';
    }else{
        echo '</tr>';
    }
    $row++;
   }

  echo '</tbody></table>';
echo '</center>';   
    fclose($handle);
 }
 ?>
mattew
  • 203
  • 1
  • 5
  • 15

2 Answers2

1
// before your while loop 
$wantedColumns = array(1,5,9,15);

// ...

for ($c=0; $c < $num; $c++) {
   if (!in_array($c,$wantedColumns)) continue;
   // ....
Steve
  • 3,601
  • 4
  • 34
  • 41
  • Perfct! It works very well Steve. Another tip, please: i want to skip the 1st row and replace with a row (header) made by myself. How to do? tks in advance!! – mattew Mar 03 '13 at 23:10
  • `if ($row == 1) { print 'myheader>'; continue; }`. – Steve Mar 03 '13 at 23:57
0

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

Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56