In today’s information era, data has become the core foundation for business decisions and management. Such data often exists as text files or spreadsheets, making PHP file reading an essential technique for importing and parsing data in web development.
The following example demonstrates the fundamental process of reading files with PHP:
Use the built-in PHP function fopen() to open a file. This function takes two parameters: the filename and the mode for opening the file (e.g., read-only, write, or read-write).
$file = fopen("data.csv", "r");
This example opens the file named data.csv in read-only mode ("r").
The fgets() function reads the file content line by line. Each call advances the file pointer to the next line until it reaches the end of the file and returns false.
while (!feof($file)) { // Check if end of file has been reached
$line = fgets($file); // Read one line from the file
echo $line . "<br>"; // Output the line with an HTML line break
}
This code outputs each line of the file separated by HTML breaks.
After finishing reading, use fclose() to close the file and free system resources.
fclose($file);
The following example shows how to read a CSV file and display its content in an HTML table:
<?php
$file = fopen("data.csv", "r");
echo "<table><tr><th>Name</th><th>Email</th></tr>";
while (!feof($file)) {
$line = fgetcsv($file);
if ($line) {
echo "<tr><td>" . htmlspecialchars($line[0]) . "</td><td>" . htmlspecialchars($line[1]) . "</td></tr>";
}
}
echo "</table>";
fclose($file);
?>
The code works as follows:
Reading files with PHP is a common data handling technique widely used in data import, parsing, and log analysis. Mastering proper file operations and best practices can greatly improve development efficiency and application performance.