文本在php中对齐csv文件阅读器

时间:2014-06-14 10:09:00

标签: php html csv

以下代码读取.csv文件并生成html表。我想决定哪个列(字段)将所有数据左对齐或居中对齐。我能怎么做?真的不知道该做什么。

<?php  
$colhead = "#9BBB59";
$colrow = "#D7E4BC";
echo "<table style=\"text-align: left; margin-left: auto; margin-right: auto; font-family: Helvetica,Arial,sans-serif; border: 1px solid black; padding:1px; border-spacing: 1px; border-collapse: separate; frame=\"border\" rules=\"none\">";
echo "<tbody>";
$row = 1;
if (($handle = fopen("myfile.csv", "r")) !== FALSE) {
 while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
    $num = count($data);
    if ($row == 1) {
        echo "<tr>";
    }else{
        echo "<tr>";
    }

    for ($c=0; $c < $num; $c++) {
        if(empty($data[$c])) {
           $value = "&nbsp;";
        }else{
           $value = $data[$c];
        }
        if ($row == 1) {

// ------------- HEADER
echo "<td style=\"background-color:$colhead; text-align:center; vertical-align:middle; color:#ffffff; font-size:16px; font-weight:bold; padding:4px;\">&nbsp;&nbsp;".$value."&nbsp;&nbsp;</td>";
 }else{

// ------------- GENERIC ROW
echo "<td style=\"background-color:$colrow; text-align:left; vertical-align:middle; color:#000000; font-size:14px; padding:4px; border:0px solid\">&nbsp;&nbsp;".$value."&nbsp;&nbsp;</td>";

        }
    }

    if ($row == 1) {
        echo '</tr>';
    }else{
        echo '</tr>';
    }
    $row++;
}

echo '</tbody></table>';
echo '</center>';   
fclose($handle);
}
?>

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

<?php
$dom = new DomDocument();
$dom -> load("file.xml");
$data = $dom->getElementsByTagName('Data'); 

$counter = 0; // Set the entry counter

echo( "<table>");

foreach($data as $node) {
    if ($counter % 3 == 0) {
        echo '<tr>';
    }

    echo "<td>". $node -> textContent . "<td>";

        if($counter % 3 == 0) {
            echo '</tr>';
        }

        $counter++; // Increment the counter
    }

    echo( "</table>");
?>

这不是最干净的代码,但应该有效。