Last active
February 15, 2022 15:05
-
-
Save 2ik/c68ed091f8db87687fc3e12d494bd719 to your computer and use it in GitHub Desktop.
PHP File Iterator Class
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 TxtFileIterator implements \Iterator | |
{ | |
protected $fileHandler; | |
protected $current; | |
protected $key; | |
function __construct(string $filePath) | |
{ | |
$this->fileHandler = fopen($filePath, "r") or die("Unable to open file!"); | |
$this->key = 0; | |
} | |
function __destruct() | |
{ | |
fclose($this->fileHandler); | |
} | |
public function current() | |
{ | |
return $this->current; | |
} | |
public function key() | |
{ | |
return $this->key; | |
} | |
public function next(): void | |
{ | |
$this->current = fgets($this->fileHandler); | |
$this->key++; | |
} | |
public function rewind(): void | |
{ | |
rewind($this->fileHandler); | |
$this->current = fgets($this->fileHandler); | |
} | |
public function valid(): bool | |
{ | |
return $this->current !== false; | |
} | |
} | |
// Example | |
$iterator = new TxtFileIterator('path/file.txt'); | |
// Use "foreach" | |
foreach ($iterator as $line) { | |
var_dump($line); | |
} | |
// Or "while" | |
$iterator->rewind(); | |
while ($iterator->valid()) { | |
$key = $iterator->key(); | |
$value = $iterator->current(); | |
var_dump($key, $value); | |
$iterator->next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment