getFileLinesGenerator.php
Table of Contents
Functions
- getFileLinesGenerator() : Generator
- Reads a file line by line and yields each line as a generator.
Functions
getFileLinesGenerator()
Reads a file line by line and yields each line as a generator.
getFileLinesGenerator(string|null $file[, callable|null $map = null ]) : Generator
Each line can optionally be transformed using a callback function. This is particularly useful for processing large files efficiently without loading the entire file into memory at once.
Example usage:
use function oihana\files\getFileLinesGenerator;
// Simply iterate over each line
foreach (getFileLinesGenerator('/path/to/file.log') as $line)
{
echo $line, PHP_EOL;
}
// Using a mapping function to parse CSV lines
foreach (getFileLinesGenerator('/path/to/data.csv', fn($line) => str_getcsv($line)) as $csvRow)
{
print_r($csvRow);
}
Parameters
- $file : string|null
-
Full path to the file to read.
- $map : callable|null = null
-
Optional mapping function applied to each line. Signature: fn(string $line): mixed
Tags
Return values
Generator —Yields each line of the file, optionally transformed by the mapping function.