public
Created

Simple CSV iterator

  • Download Gist
CSVIterator.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
<?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;

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.