How to change one particular column's background color when importing data from a CSV

2.2k views Asked by At

I am importing CSV data into a HTML table using this solution. Right now the table has 7 columns (but the number of rows will vary from 20-60 time to time). My client asked me to change the 5th column's background color to something else so that one particular column stands out from the rest. How can I do that?

My code:

 <?php
 $f = fopen("so-csv.csv", "r");
 while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
       echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>\n";
 }
 fclose($f);
 ?>

UPDATE

Thank you roullie & Ghost for your quick responses! However, I forgot to mention that my client wants the table to have 2 colors, e.g. if all the columns are red, only the 5th one will be gray. So I had...

foreach ($line as $cell) {
  echo '<td style="background-color: #892525;">' . htmlspecialchars($cell) . '</td>';
}

Now how can I add your solution to this?

2

There are 2 answers

4
Kevin On BEST ANSWER

Just add a key checking while inside the foreach loop:

foreach ($line as $k => $cell) {
   // index starts at zero
   $color = ($k == 4) ? '#ccc;' : '#892525;';
   $class = "style='background-color: $color'";
   echo "<td $class>" . htmlspecialchars($cell) . "</td>";
}
0
roullie On
    <?php
 $five = 5;
 $ctr = 1;
 $f = fopen("so-csv.csv", "r");
 while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
       echo "<td ".($ctr==$five?"style='background:red":"").">" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>\n";
    $ctr++;
 }
 fclose($f);
 ?>