Skip to content

Instantly share code, notes, and snippets.

@mattattui
Created February 19, 2013 23:18
Show Gist options
  • Save mattattui/4991169 to your computer and use it in GitHub Desktop.
Save mattattui/4991169 to your computer and use it in GitHub Desktop.
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