如何使用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.