Current Location: Home> Latest Articles> How to Extract and Display Data from CSV Files Using PHP

How to Extract and Display Data from CSV Files Using PHP

gitbox 2025-06-18

What is a CSV File?

CSV (Comma-Separated Values) is a popular file format that stores tabular data as plain text. It is commonly used for spreadsheet exports, databases, and is highly compatible across different platforms.

CSV files are simple to use and highly portable, making them widely applied in business, research, and data analysis fields. They are a key source for data processing, analysis, and mining.

How to Extract and Display Data from CSV Files Using PHP?

In PHP development, reading and displaying data from CSV files is a common task. PHP provides built-in functions for file reading and processing, which makes it easy to extract CSV data and display it as an HTML table.

Step 1: Reading the CSV File

In PHP, the fopen()

In this code, we first use fopen() to open the "data.csv" file in read-only mode ("r"). Then, we use the fgetcsv() function to read the file line by line, storing each line's data into the $data array. Finally, fclose() is used to close the file.

Step 2: Displaying CSV Data

To present CSV data on a webpage as a table, we can use PHP arrays and loops. The following code demonstrates how to convert the CSV data into an HTML table:


echo "<table>";
foreach ($data as $row) {
    echo "<tr>";
    foreach ($row as $cell) {
        echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

This code uses foreach to loop through each row in the $data array and generates a table row for each. It also uses htmlspecialchars() to prevent XSS attacks by escaping special characters in HTML.

Complete Code Example

Here is the complete PHP code example that combines both steps of reading and displaying CSV data:


$file = fopen("data.csv", "r");
$data = [];
while (!feof($file)) {
    $line = fgetcsv($file);
    array_push($data, $line);
}
fclose($file);

echo "<table>";
foreach ($data as $row) {
    echo "<tr>";
    foreach ($row as $cell) {
        echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

This complete code reads the CSV file, stores the data as a two-dimensional array, and then loops through the array to display the data as an HTML table.

Conclusion

This article introduced how to extract and display data from CSV files using PHP. We first read the CSV file using fopen() and fgetcsv(), then use loops and HTML generation to display the CSV data in a table format. By mastering these techniques, you can efficiently handle CSV data and present it in a clean, user-friendly way.