如何使用PHP显示CSV文件中的数据?


在这篇文章中,我们将学习如何使用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

在这个例子中,我们将读取一个包含学生姓名、年龄和性别的Students CSV文件,我们将分别使用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的fgetcsv()函数显示CSV文件中的数据是一个简单的过程。借助HTML标签,我们可以轻松地以表格格式显示数据。通过本文提供的示例,我们学习了如何在PHP中读取和显示CSV文件中的数据,这在各种应用程序中都非常有用。

更新于:2023年8月2日

3K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.