在网页上动态显示CSV文件作为HTML表格

dre*_*ves 30 html php csv

我想将CSV文件放在服务器端,并将其作为html表动态显示.例如,这个:

Name, Age, Sex
"Cantor, Georg", 163, M
Run Code Online (Sandbox Code Playgroud)

应该成为这样的:

<html><body><table>
<tr> <td>Name</td> <td>Age</td> <td>Sex</td> </tr>
<tr> <td>Cantor, Georg</td> <td>163</td> <td>M</td> </td>
</table></body></html>
Run Code Online (Sandbox Code Playgroud)

欢迎任何语言的解决方案.

phi*_*hag 91

所述先前连接的溶液是一种可怕的一段代码; 几乎每一行都包含一个bug.请改用fgetcsv:

<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.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></body></html>";
Run Code Online (Sandbox Code Playgroud)


Job*_*eph 13

这是一个使用php将csv转换为html表的简单函数:

function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table>';
//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);
}
Run Code Online (Sandbox Code Playgroud)

人们可以称之为这个功能 jj_readcsv('image_links.csv',true);

如果第二个参数为true,那么csv的第一行将被视为标题/标题.

希望这有助于某人.请评论此代码中的任何缺陷.


小智 6

phihag 的回答将每一行放在一个单元格中,而您要求将每个值放在一个单独的单元格中。这似乎做到了:

<?php
// Create a table from a csv file 
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        $row = $line[0];    // We need to get the actual row (it is the first element in a 1-element array)
        $cells = explode(";",$row);
        echo "<tr>";
        foreach ($cells as $cell) {
            echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
Run Code Online (Sandbox Code Playgroud)