Read a plain text file with php

Read a plain text file with php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Reading Plain Text Files in PHP: A Practical Guide

When you need to process a text file containing a vertical list of data—like Data1, Data2, and so on—the most straightforward approach is to read the file line by line. This prevents loading an entire massive dataset into memory at once, which is crucial when dealing with large logs or configuration dumps. The core tool for this in PHP is the file() function combined with array manipulation, or using fopen/fgets for more granular control.

The Simple Approach: Using file()

For most standard use cases where you just need to iterate over lines without seeking specific offsets, the file() function is your best starting point. It reads the entire file and returns an array of lines. Crucially, this function automatically appends a newline character (\n) to each line in the returned array. This means if your source data has empty lines or trailing newlines, they are preserved as empty strings in the resulting array.

Here is a robust pattern for reading such a file:

$filename = 'data.txt';
$lines = file($filename);

foreach ($lines as $line) {
    // Remove the trailing newline to get just the data
    $cleanLine = rtrim($line, "\n"); 
    
    // Process $cleanLine here
    echo "Processing: {$cleanLine}\n";
}

In this example, rtrim() strips the automatic newline. If you need the raw string without any trimming logic inside your loop, you can disable the newline append by passing a second argument to file(). Setting it to false returns an array where each element contains the file contents up to (and including) the last newline character, effectively removing the trailing newline from every line automatically.

$lines = file($filename, false); 
// $lines[0] is now exactly "Data1" without a newline

Handling Large Files with fopen and fgets

While file() is convenient, it loads the whole file into memory. If your text file contains millions of lines or gigabytes of data, this approach will cause a Memory Limit Exceeded error. In production environments where file size is unpredictable, using the file pointer functions is the safer architectural choice.

You open the file handle, read a chunk (line), process it, and then discard it immediately before reading the next one. This keeps memory usage constant regardless of file size.

$handle = fopen($filename, 'r');

while (($line = fgets($handle)) !== false) {
    // $line includes the newline character
    if (trim($line) === '') {
        continue; // Skip empty lines
    }
    
    // Process data
    echo $line;
}

fclose($handle);

This method is significantly more memory-efficient. It allows you to process streaming data or log files indefinitely without hitting PHP's memory_limit configuration.

Parsing CSV vs. Plain Text

It is vital to distinguish between plain text and CSV (Comma Separated Values). The source material describes a simple vertical list, which implies a single column of text. If your file actually contains structured data like Name,Age,City, using the methods above will result in malformed data because they treat the entire line as a single string.

For true CSV files, you must use the str_getcsv() function or the dedicated CsvFile helper class available in Laravel. The file() approach fails here because it doesn't handle delimiters and quoting logic internally. If you are building an application that needs to handle both raw text logs and structured CSV exports, ensure your code path detects the file type before choosing the parsing strategy.

Performance Considerations

When choosing between file() and fopen(), consider the trade-off between code simplicity and resource constraints. file() is faster for small files because it avoids the overhead of opening/closing the handle repeatedly inside a loop (though you only open once in the example above, the internal buffering differs). However, if your application runs on shared hosting with strict memory limits, or processes sensitive logs that shouldn't linger in RAM, the stream-based approach is mandatory.

Always ensure the file exists and is readable before attempting to open it to prevent fatal errors in production environments.

For further resources on building scalable PHP applications and leveraging modern frameworks like Laravel for robust file handling, check out LaravelCompany.

Our network