Created
February 19, 2013 23:18
-
-
Save mattattui/4991169 to your computer and use it in GitHub Desktop.
Simple CSV iterator
This file contains hidden or 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 | |
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