Skip to content

Instantly share code, notes, and snippets.

@2ik
Last active February 15, 2022 15:05
Show Gist options
  • Save 2ik/c68ed091f8db87687fc3e12d494bd719 to your computer and use it in GitHub Desktop.
Save 2ik/c68ed091f8db87687fc3e12d494bd719 to your computer and use it in GitHub Desktop.
PHP File Iterator Class
<?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