PHP – Big File Operation with Generator

<?php
class CsvReader
{
    protected $file;
 
    public function __construct($filePath) {
        $this->file = fopen($filePath, 'r');
    }
 
    public function rows()
    {
        while (!feof($this->file)) {
            $row = fgetcsv($this->file, 4096);

            yield $row;
        }
        
    }
}
 
$csv = new CsvReader('/path/to/big/csv/file.csv');

foreach ($csv->rows() as $row) {
    // the CSV row.
}

Views: 239