Skip to content

Instantly share code, notes, and snippets.

@arth2o
Last active November 20, 2015 14:54
Show Gist options
  • Save arth2o/2d17b9add4d38a6f9bff to your computer and use it in GitHub Desktop.
Save arth2o/2d17b9add4d38a6f9bff to your computer and use it in GitHub Desktop.
PHP yield example to open big file and stream line by line
<?php
/**
* Class File
*/
class File
{
private $fileName;
private $file;
public function __construct($fileName)
{
$this->fileName = $fileName;
$this->openDb();
}
/**
* @return \Generator
* read line by line use less memory
*/
public function getLine()
{
while (($line = fgets($this->file)) !== false) {
if (!empty($line)) {
yield $line;
} else {
$this->closeDb();
}
}
}
private function openDb()
{
$this->file = fopen($this->getFileName(), 'r');
}
private function closeDb()
{
fclose($this->file);
}
public function getFileName()
{
return $this->fileName;
}
public function getFile()
{
return $this->file;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment