Skip to content

Instantly share code, notes, and snippets.

@nhtahoe
Last active September 10, 2019 16:31
Show Gist options
  • Save nhtahoe/b665b9dd1bedb3e017effc0f724f5df3 to your computer and use it in GitHub Desktop.
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
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