Last active
June 23, 2021 14:59
-
-
Save szabacsik/04ff5e1d0f0d9d018a716598b4b4ef74 to your computer and use it in GitHub Desktop.
PHP CSV file iterator
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 | |
//https://www.linkedin.com/learning/advanced-php/create-an-iterator?u=2113185 | |
class CsvIterator extends IteratorIterator | |
{ | |
public function __construct(string $path) | |
{ | |
parent::__construct(new SplFileObject($path, 'r')); | |
$file = $this->getInnerIterator(); | |
$file->setFlags(SplFileObject::READ_CSV); | |
$file->setCsvControl(',', '"', "\\"); | |
} | |
} | |
class FilterRows extends FilterIterator | |
{ | |
public function accept(): bool | |
{ | |
$current = $this->getInnerIterator()->current(); | |
if (count($current) == 1) { | |
return false; | |
} | |
return true; | |
} | |
} | |
$csvIterator = new CsvIterator('data.csv'); | |
$csvIterator = new FilterRows($csvIterator); | |
foreach ($csvIterator as $index => $row) { | |
var_dump($row); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment