Last active
September 10, 2019 16:31
-
-
Save nhtahoe/b665b9dd1bedb3e017effc0f724f5df3 to your computer and use it in GitHub Desktop.
Returns a Generator representation of file lines that we can then iterator over with foreach
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
if (!function_exists('getFileLines')) { | |
/** | |
* Returns a Generator representation of file lines that we can then iterator over with foreach | |
* | |
* eg: | |
* $fileData = getFileLines('path.txt'); | |
* foreach ($fileData() as $line) { | |
* // $line contains current line | |
* } | |
* | |
* @param string $path | |
* | |
* @return Closure | |
*/ | |
function getFileLines(string $path) | |
{ | |
return function () use ($path) { | |
$file = fopen($path), 'r')); | |
if (!$file) | |
die('file does not exist or cannot be opened'); | |
while (($line = fgets($file)) !== false) { | |
yield preg_replace("/[\n\r]/","",$line); // strip carriage returns and new lines while we're at it | |
} | |
fclose($file); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment