使用php从CSV文件生成彩色表格

时间:2011-03-11 18:53:00

标签: php html-table import-from-csv

首先,我想说我刚开始使用PHP,所以请善待。我想要做的是从csv文件打印一个表。第一行我想用灰色背景颜色加粗。下一行应与白色和绿色背景交替,文本不是粗体。下面是我的尝试,但它只是生成一个包含灰色背景的所有粗体文本的表

<?php
echo "<html><body><table>\n\n";
$f = fopen("acsv.csv", "r");

$green = "#DDFFCC";
$white = "#FFFFFF";
$grey = "#EEEEEE";
$color = "#EEEEEE";
echo "<table border=1 cellpadding=4 cellspacing=0>";
echo "<tr>";



while (($line = fgetcsv($f)) !== false) {


        foreach ($line as $cell) {
                if ($color = "#EEEEEE"){
                    echo "<td bgcolor= ".$color."><b>" . htmlspecialchars($cell) . "</b></td>";
                }
                else{
                    echo "<td bgcolor= ".$color.">" . htmlspecialchars($cell) . "</td>";
                }

        }
        echo "<tr>\n";

        switch($color){
            case "#EEEEEE":
                $color = "#FFFFFF";
                break;
            case "#FFFFFF":
                $color = "#DDFFCC";
                break;
            case "#DDFFCC":
                $color = "#FFFFFF";
                break;
        }
}
fclose($f);
echo "\n</table></body></html>";

编辑:

我还想知道如何使用有意义的名称定义颜色以使代码更具可读性

3 个答案:

答案 0 :(得分:3)

要检查$ color是否设置为“#EEEEEE”,您需要在if statement中使用double equals(==),类似于C / C ++ / C#。否则,你只是告诉PHP将$ color设置为“#EEEEEE”。

if ($color == "#EEEEEE"){ 

答案 1 :(得分:0)

switch语句需要在foreach中,否则颜色只会在循环完成迭代后改变。

<?php
echo "<html><body><table>\n\n";
$f = fopen("acsv.csv", "r");

$green = "#DDFFCC";
$white = "#FFFFFF";
$grey = "#EEEEEE";
$color = "#EEEEEE";
echo "<table border=1 cellpadding=4 cellspacing=0>";
echo "<tr>";



while (($line = fgetcsv($f)) !== false) {


        foreach ($line as $cell) {
        if ($color == "#EEEEEE"){
                echo "<td bgcolor= ".$color."><b>" . htmlspecialchars($cell) . "</b></td>";
            }
            else{
                echo "<td bgcolor= ".$color.">" . htmlspecialchars($cell) . "</td>";
            }
        switch($color){
            case "#EEEEEE":
                $color = "#FFFFFF";
                break;
            case "#FFFFFF":
                $color = "#DDFFCC";
                break;
            case "#DDFFCC":
                $color = "#FFFFFF";
                break;
        }



        }
        echo "</tr><tr>\n";

}
fclose($f);
echo "\n</table></body></html>";

答案 2 :(得分:0)

您需要关闭代码:

foreach ($line as $cell) {
                if ($color = "#EEEEEE"){
                    echo "<td bgcolor= ".$color."><b>" . htmlspecialchars($cell) . "</b></td>";
                }
                else{
                    echo "<td bgcolor= ".$color.">" . htmlspecialchars($cell) . "</td>";
                }

        }
        echo "`</tr>`<tr>\n";