Avatar ·

How to efficiently read a large file line by line in PHP without memory overload?

Hello everyone! I'm a beginner PHP developer and I've encountered a problem when processing large files. I have a CSV file about 200 MB in size that needs to be processed line by line. First I tried using file_get_contents() and explode() by newline character, but the script crashes with an "Allowed memory size exhausted" error. Here's my code: ```php $data = file_get_contents('big_file.csv'); $lines = explode("\n", $data); foreach ($lines as $line) { // Process the line echo $line . "\n"; } ``` I understand that file_get_contents() loads the entire file into memory, which causes the problem. But how do I properly read a file line by line? I've heard about fopen() and fgets(), but I'm not sure how to use them correctly for large files. I'm also interested in how to process files of different sizes.