How can streaming be a better option than loading large files into memory all at once in PHP?

Loading large files into memory all at once can lead to memory exhaustion, especially when dealing with very large files. Streaming allows you to read and process the file in smaller chunks, reducing memory usage and improving performance. This can be achieved in PHP using functions like fopen, fread, and fclose to read and process the file chunk by chunk.

$filePath = 'path/to/large/file.txt';

$handle = fopen($filePath, 'r');
if ($handle) {
    while (!feof($handle)) {
        $chunk = fread($handle, 1024); // Read 1KB at a time
        // Process the chunk here
    }
    fclose($handle);
}