Skip to content

@inanimatt /CSVIterator.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Simple CSV iterator
<?php
class CSVIterator extends SPLFileObject
{
protected $first_row = true;
protected $columns;
public function __construct ($filename, $delimiter = ',')
{
parent::__construct($filename);
$this->setFlags(SPLFileObject::READ_CSV);
$this->setCsvControl($delimiter);
}
public function current()
{
// Set the column names if first row
// FIXME: assumes the first row is a header
if ($this->first_row) {
$this->first_row = false;
$this->columns = parent::current();
$this->next();
}
$row_data = parent::current();
// Stop at end of file
if (!$this->valid()) {
return;
}
return array_combine($this->columns, $row_data);
}
}
// Test
$file = new CSVFile('testset.csv');
foreach($file as $idx => $row) {
if ($idx % 10000 == 0) {
echo '.';
}
}
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.