PHP 显示 CSV 文件为表格:简单代码示例
以下是一个简单的 PHP 代码示例,用于显示 CSV 文件并将其以表格形式呈现:
<?php
$file = 'data.csv'; // CSV 文件路径
// 读取 CSV 文件
$data = array_map('str_getcsv', file($file));
// 获取表头
$headers = array_shift($data);
// 输出 HTML 表格
echo '<table>';
echo '<tr>';
foreach ($headers as $header) {
echo '<th>' . $header . '</th>';
}
echo '</tr>';
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
这个示例代码会读取名为'data.csv'的 CSV 文件,并将其转换为一个二维数组。然后,它会使用 HTML 表格标签来呈现 CSV 数据,其中第一行为表头,其余行为数据行。
原文地址: https://www.cveoy.top/t/topic/mNTv 著作权归作者所有。请勿转载和采集!