Last active
November 20, 2015 14:54
-
-
Save arth2o/2d17b9add4d38a6f9bff to your computer and use it in GitHub Desktop.
PHP yield example to open big file and stream line by line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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