如何使用 PHP 显示 CSV 文件中的数据?
phpserver side programmingprogramming更新于 2025/5/7 16:07:17
在本文中,我们将学习如何使用 PHP 的 fgetcsv()、str_getcsv 和 SplFileObject 函数显示 CSV 文件中的数据。
CSV 文件是一种简单的文件格式,用于存储以逗号分隔的值的数据,其中的每一行代表表格数据中的一条记录。要使用 PHP 读取 CSV 文件,我们将使用 fgetcsv() 函数,该函数从 CSV 文件中读取一行并返回表示该行中存在的 CSV 数据的值数组。
让我们借助下面的示例来理解这一点 -
示例 1
在此示例中,我们将使用 fgetcsv() 函数读取数据 CSV 文件,并使用 HTML 表格标记以表格格式显示值。
本例中使用的 CSV 文件 -
Data.csv
Name, Age, City John, 30, New York Mary, 25, Los Angeles Tom, 40, Chicago
文件名:index.php
<html lang="en">
<head>
<title>How to Display Data from CSV file using PHP?</title>
</head>
<body>
<h3>How to Display Data from CSV file using PHP?</h3>
<?php
$csvFile = fopen('Data.csv', 'r');
echo '<table>';
while (($data = fgetcsv($csvFile, 1000, ",")) !== FALSE) {
echo '<tr>';
foreach ($data as $value) {
echo '<td>' . htmlspecialchars($value) . '</td>';
}
echo '</tr>';
}
echo '</table>';
fclose($csvFile);
?>
</body>
</html>
示例 2
在此示例中,我们将读取包含学生姓名、年龄和性别的学生 CSV 文件,并使用 3 种不同的方法以表格格式显示他们的数据,分别使用 str_getcsv、fgetcsv 和 SplFileObject 方法。
Students.csv
Name,Age,Gender John Doe,25,Male Jane Smith,30,Female Bob Johnson,40,Male Sara Lee,22,Female
文件名:index.php
<html lang="en">
<head>
<title>How to Display Data from CSV file using PHP?</title>
</head>
<body>
<h3>How to Display Data from CSV file using PHP?</h3>
<!-- Method 1: str_getcsv -->
<?php
$csvData = file_get_contents('students.csv');
$rows = str_getcsv($csvData, "
"); // Split CSV data into rows
echo '<h4>Method 1: str_getcsv</h4>';
echo '<table>';
echo '<thead><tr><th>Name</th><th>Age</th><th>Gender</th></tr></thead>';
echo '<tbody>';
foreach ($rows as $row) {
$values = str_getcsv($row, ","); // Split row into values
echo '<tr>';
foreach ($values as $value) {
echo '<td>' . htmlspecialchars($value) . '</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
?>
<!-- Method 2: Combine fgetcsv() and HTML -->
<?php
echo '<h4>Method 2: Combine fgetcsv() and HTML</h4>';
$csvFile = fopen('students.csv', 'r');
echo '<table>';
echo '<thead><tr><th>Name</th><th>Age</th><th>Gender</th></tr></thead>';
echo '<tbody>';
while (($data = fgetcsv($csvFile, 1000, ",")) !== FALSE) {
echo '<tr>';
foreach ($data as $value) {
echo '<td>' . htmlspecialchars($value) . '</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
fclose($csvFile);
?>
<!-- Method 3: using SplFileObject -->
<?php
echo '<h4>Method 3: using SplFileObject</h4>';
$csvFile = new SplFileObject('students.csv', 'r');
$csvFile->setFlags(SplFileObject::READ_CSV);
echo '<table>';
echo '<thead><tr><th>Name</th><th>Age</th><th>Gender</th></tr></thead>';
echo '<tbody>';
foreach ($csvFile as $row) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . htmlspecialchars($value) . '</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
?>
结论
总之,使用 PHP 显示 CSV 文件中的数据是一个简单的过程,使用 fgetcsv() 函数。借助 HTML 标签,我们可以轻松地以表格格式显示数据。通过遵循本文提供的示例,我们学会了在 PHP 中读取和显示 CSV 文件中的数据,这在各种应用程序中都很有用。

