タイトル通り、PHPでファイルを1行ごと読み込むためのIteratorをSplFileObjectを使って実装してみました。
<?php
class TextFileRowIterator implements \Iterator {
private ?\SplFileObject $file;
private $filePath;
private $current;
private $lineNumber = 0;
public function __construct($filePath) {
$this->filePath = $filePath;
}
public function current() {
return $this->current;
}
public function key(): \scalar {
return $this->lineNumber;
}
public function next(): void {
$this->lineNumber++;
// 応用例として、SplFileObjectの呼び出すメソッドを、fgetcsvに変えるとcsvファイルを1行ごと配列で読み込むことができます。
$this->current = str_replace(["\r", "\n"], '', $this->file->fgets());
}
public function rewind(): void {
$this->file = null;
$this->file = new \SplFileObject($this->filePath);
$this->lineNumber = 0;
if(!$this->file->eof())
{
$this->next();
}
}
public function valid(): bool {
return $this->file->valid();
}
}
下記のようにforeachで呼び出して使います。
$path = '/tmp/test.txt';
foreach(new TextFileRowIterator($path) as $row)
{
echo $row."\n";
}
コメント