Vera width of large files in PHP using generator


To process large amounts of data with PHP you need much memory memory, because large amounts of data are loaded and then processed. A memory-efficient alternative Generators from PHP 5.5., the yield Command through large amounts of data can iterate and occupy only space for a data set.

Example: Process a large CSV file using generator:

<?php
class CsvFile {

    protected $file;

    public function __construct($file) {
        $this->file = fopen($file, 'r');
    }

    public function parse() {
        while (!feof($this->file)) {
            yield fgetcsv($this->file);
        }
        return;
    }
}

$csv = new CsvFile('/pathTo/file.csv');
foreach ($csv->parse() as $row) {
    echo $row;
}