TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

PHP Generator - reading file content

In PHP, to fetch content from a file, a common implementation is to loop its content and store them in a temporary variable. In today's tutorial, we want to introduce a solution by using the generator.

Read file using a loop

Normal we will load the file content to memory and read its content using a loop.

$m1 = memory_get_peak_usage();
foreach (file('lorem.txt') as $l);
$m2 = memory_get_peak_usage();
echo $m2 - $m1."\n";
 
// Output
1542736

Read file using a generator

We can do the same using a generator function. Inside the function, we open the file and yield its content line by line:

function file_lines($filename) {
    $file = fopen($filename, 'r');
    while (($line = fgets($file)) !== false) {
        yield $line;
    }
    fclose($file);
}
 
 
$m1 = memory_get_peak_usage();
foreach (file_lines('lorem.txt') as $l);
$m2 = memory_get_peak_usage();
echo $m2 - $m1."\n";
 
// Ouput
0

Generator

As we can see, when using a generator, we have greatly reduced memory usage.

The reason is that when we yield results from a generator function, it saves its current state until it is called next time.

The end

Hopefully this simple tutorial helped you with your development.