PHP fgetcsv仅显示特定列

时间:2014-05-07 16:42:48

标签: php fgetcsv

我使用下面的代码(来自上一篇文章)从csv文件中提取但我只想显示特定的列。我已经尝试使用其他解决方案进行修改但无济于事。任何帮助都会非常有用。

<?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 |栏3
COLUMN1 | COLUMN3 |栏3

摘要:我只想显示1&amp; 2

1 个答案:

答案 0 :(得分:1)

假设您不想显示第二列,请遍历数字索引数组并排除您想要的数组,例如:

  <?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);
}
?>