Current Location: Home> Latest Articles> PHP File Reading Guide: Step-by-Step for Data Import and Content Parsing

PHP File Reading Guide: Step-by-Step for Data Import and Content Parsing

gitbox 2025-06-10

Introduction

Reading file contents is a common requirement in web development. PHP, as a widely used server-side scripting language, offers a variety of functions to easily read and process file data. This article will explain how to use PHP to read and parse file contents, facilitating data import and subsequent processing.

Steps

1. Open the File

First, use the fopen() function to open the file and get a file pointer for further operations. This function accepts two parameters: the filename and the mode to open the file.

Common file modes include:

  • r: read-only, starting from the beginning of the file.
  • r+: read and write, starting from the beginning.
  • w: write-only, truncates the file or creates a new one.
  • w+: read and write, truncates or creates the file.
  • a: write-only, appends to the end or creates the file.
  • a+: read and write, appends to the end or creates the file.

Example code:

$filename = 'data.txt';
$fp = fopen($filename, 'r');

2. Read File Content

With the file pointer, you can call various PHP functions to read file contents as needed:

  • fread($fp, $length): read a specified length of data.
  • fgets($fp): read line by line.
  • fgetc($fp): read character by character.
  • file($filename): reads the whole file into an array, each element is a line.
  • file_get_contents($filename): reads the entire file as a string at once.

Example using fread():

$filename = 'data.txt';
$fp = fopen($filename, 'r');
$content = fread($fp, filesize($filename));
fclose($fp);

3. Parse File Content

After reading, you often need to parse the content to extract useful information. Here we take CSV files as an example. CSV is a comma-separated text format widely used for tabular data exchange.

Assume the CSV file contents are as follows:

name,age,gender
John,30,Male
Alice,25,Female
Bob,36,Male

PHP’s built-in fgetcsv() function can easily read and parse each line of a CSV file:

$filename = 'data.csv';
$fp = fopen($filename, 'r');
while (($data = fgetcsv($fp)) !== false) {
    echo 'Name: ' . $data[0] . '
';
    echo 'Age: ' . $data[1] . '
';
    echo 'Gender: ' . $data[2] . '
';
}
fclose($fp);

4. Close the File

After finishing file operations, always call fclose() to close the file pointer and free system resources:

fclose($fp);

Conclusion

This article introduced the complete process of reading files with PHP, including opening files, reading content, parsing data, and closing files. Choosing the right reading and parsing methods according to the file format and requirements is crucial. Mastering these fundamental skills is essential for web developers handling data processing.