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.
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:
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.
Hopefully this simple tutorial helped you with your development.