Skip to content
PHP Logo

How can PHP be used to read CSV files and display the content in HTML tables?

To read CSV files and display the content in HTML tables using PHP, you can use the fgetcsv() function to read the CSV file line by line and explode() function to split the CSV data into an array. Then, you can iterate through the data and output it within an HTML table structure.

php
<?php

// Open the CSV file for reading
$csvFile = fopen('file.csv', 'r');

// Initialize an empty array to store the CSV data
$data = [];

// Read the CSV file line by line
while (($row = fgetcsv($csvFile)) !== false) {
    $data[] = $row;
}

// Close the CSV file
fclose($csvFile);

// Output the CSV data in an HTML table
echo '<table>';
foreach ($data as $row) {
    echo '<tr>';
    foreach ($row as $cell) {
        echo '<td>' . htmlspecialchars($cell) . '</td>';
    }
    echo '</tr>';
}
echo '</table>';

?>