php导入csv第一行表头

时间:2016-10-25 08:22:39

标签: php csv

我有一个csv文件,我将在php页面上导入。但他必须将第一行设置为表头(th)。 我使用这个脚本但是现在我只有表行(tr)

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

有人可以帮助我使用此代码将第一行设置为标题,其余部分设置为tr。

由于

1 个答案:

答案 0 :(得分:0)

$flag = true;
while(..) {
    if($flag) { 
        // Proceed header here
        $flag = false; 
        continue; 
    }
    // the rest rows
}

<强>更新

echo "<table class='table table-striped table-hover'>\n\n";
$f = fopen("myfile.csv", "r");
$flag = true;
while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    if($flag) { 
        // Proceed header here
        foreach ($line as $cell) {
            echo "<th>" . htmlspecialchars($cell) . "</th>";
        }
        echo "</tr>\n";
        $flag = false; 
        continue; 
    }

    foreach ($line as $cell) {
        echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>\n";
}
fclose($f);
echo "\n </table>";
相关问题