Current Location: Home> Latest Articles> Complete Guide to PHP File Reading: Practical Data Import and CSV Parsing

Complete Guide to PHP File Reading: Practical Data Import and CSV Parsing

gitbox 2025-06-07

1. Application Scenarios of PHP File Reading

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.

2. Basic Steps of PHP File Reading

The following example demonstrates the fundamental process of reading files with PHP:

2.1 Opening a File

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").

2.2 Reading the File Line by Line

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.

2.3 Closing the File

After finishing reading, use fclose() to close the file and free system resources.


fclose($file);

3. Example: Reading CSV Files in PHP

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:

  • Open the CSV file with fopen().
  • Output an HTML table with headers for Name and Email.
  • Use fgetcsv() to read each CSV row as an array, safely outputting the fields into table cells.
  • Close the file after finishing.

4. Important Considerations for PHP File Reading

  • Ensure the correct filename and access mode are specified when opening files.
  • Always check for end-of-file to avoid infinite loops.
  • For CSV files, confirm the field delimiter and text enclosure characters are correct (commonly comma and double quotes).
  • For large files, consider using stream-based reading methods like fread() for better performance.
  • Implement proper error handling to avoid crashes due to missing files or permission issues.

5. Conclusion

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.