Skip to content

Instantly share code, notes, and snippets.

@szabacsik
Last active June 23, 2021 14:59
Show Gist options
  • Save szabacsik/04ff5e1d0f0d9d018a716598b4b4ef74 to your computer and use it in GitHub Desktop.
Save szabacsik/04ff5e1d0f0d9d018a716598b4b4ef74 to your computer and use it in GitHub Desktop.
PHP CSV file iterator
<?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