【问题标题】:php import csv first row table headerphp导入csv第一行表头
【发布时间】:2016-10-25 08:22:39
【问题描述】:

我有一个 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。

谢谢

【问题讨论】:

    标签: php csv


    【解决方案1】:
    $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>";
    

    【讨论】:

    • \n\n"; $f = fopen("myfile.csv", "r"); while (($line = fgetcsv($f)) !== false) { echo ""; foreach ($line as $cell) { echo "" . htmlspecialchars($cell) 。 ""; } 回声 "\n"; } fclose($f); echo "\n ";?>
    • ' 摘要 状态 优先级 受让人 已创建 已更新 2 '
    • 新问题 :-)
    猜你喜欢
    • 2013-02-05
    • 2012-08-29
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 2017-09-21
    相关资源
    最近更新 更多