-
Notifications
You must be signed in to change notification settings - Fork 0
FileReader
Ray Fung edited this page Feb 26, 2026
·
3 revisions
The FileReader class provides a memory-efficient, line-by-line file reader powered by PHP generators. It supports concatenating multiple files into a single sequential stream.
| Method | Return | Description |
| --- | --- | --- |
| __construct(string $filePath) | — | Open the first file for reading |
| append(string $filePath) | FileReader | Append another file to the read queue |
| prepend(string $filePath) | FileReader | Prepend another file before the current queue |
| fetch() | ?string | Return the next line, or null when exhausted |
use Razy\FileReader;
$reader = new FileReader('/path/to/data.txt');
// Read line by line
while (($line = $reader->fetch()) !== null) {
echo $line . "\n";
}Chain multiple files together — they are read sequentially as a single stream:
$reader = new FileReader('/logs/app-2026-01.log');
$reader->append('/logs/app-2026-02.log')
->append('/logs/app-2026-03.log');
// Reads all three files in order
while (($line = $reader->fetch()) !== null) {
// Process each line from all files
}$reader = new FileReader('/data/main.csv');
// Add a header file before the main data
$reader->prepend('/data/header.csv');
// Reads header.csv first, then main.csv
while (($line = $reader->fetch()) !== null) {
$fields = str_getcsv($line);
// Process CSV row
}use Razy\FileReader;
$reader = new FileReader('/data/users.csv');
$headers = null;
$users = [];
while (($line = $reader->fetch()) !== null) {
$row = str_getcsv($line);
if ($headers === null) {
$headers = $row;
continue;
}
$users[] = array_combine($headers, $row);
}use Razy\FileReader;
$reader = new FileReader('/var/log/app/error.log');
$errors = [];
while (($line = $reader->fetch()) !== null) {
if (str_contains($line, '[ERROR]')) {
$errors[] = $line;
}
}
echo 'Found ' . count($errors) . ' errors';use Razy\FileReader;
// Merge daily report files into a single stream
$reader = new FileReader('/reports/day1.csv');
$reader->append('/reports/day2.csv')
->append('/reports/day3.csv');
$totalRows = 0;
while ($reader->fetch() !== null) {
$totalRows++;
}
echo "Processed $totalRows lines across 3 files";