سؤال

I'm using the code below (from a previous post) to pull from an csv file but I'd like to just display specific columns. I've already tried to modify using other solutions with no avail. Any help would be much appriciated.

<?php 
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table width="400" border="1" bordercolor="#666666" cellspacing="0" cellpadding="2">';
//display header row if true
if ($header) {
    $csvcontents = fgetcsv($handle);
    echo '<tr>';
    foreach ($csvcontents as $headercolumn) {
    echo "<th>$headercolumn</th>";
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
    echo '<tr>';
    foreach ($csvcontents as $column) {
       echo "<td>$column</td>";
    }
    echo '</tr>';
}
echo '</table>';
fclose($handle);
}
?>

HEADER1 | HEADER2 | HEADER3
COLUMN1 | COLUMN2 | COLUMN3
COLUMN1 | COLUMN3 | COLUMN3

Summary: I just want to display 1&2

هل كانت مفيدة؟

المحلول

Assuming you dont want to display the second column, iterate through the numerically indexed array and exclude the ones you want, something like:

  <?php 
  function jj_readcsv($filename, $header=false) {
  $handle = fopen($filename, "r");
  echo '<table width="400" border="1" bordercolor="#666666" cellspacing="0" cellpadding="2">';
  //display header row if true
 if ($header) {
  $csvcontents = fgetcsv($handle);
  echo '<tr>';
  foreach ($csvcontents as $k => $v) {
    if ($k != 1) {
        echo "<th>$vth>";
    }
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $k => $v) {
   if ($k != 1) {
        echo "<td>$v</td>";
    }
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
?>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top