Skip to content

Instantly share code, notes, and snippets.

@stephenheard
Last active December 27, 2015 17:58
Show Gist options
  • Save stephenheard/7365794 to your computer and use it in GitHub Desktop.
Save stephenheard/7365794 to your computer and use it in GitHub Desktop.
Very simple CSV parser object in PHP. Pass it a CSV string, perhaps from a file_get_contents($path)Requires that the first row be the column names, and that the delimiter is a comma.
<?php
class CSV implements IteratorAggregate {
// this is where we will store the rows
protected $rows = array();
function __construct($csv)
{
// split up the csv string into individual lines
$lines = explode(PHP_EOL, $csv);
// we're assuming the first row is the column names. split them up.
$fields = explode(',', $lines[0]);
// iterate through the rest of the rows
for ($i = 1; $i < count($lines) - 1; $i++)
{
// instantize a holder class
$row = new stdClass;
// split up the row data
$rowData = explode(',', $lines[$i]);
// iterate through each column
foreach ($fields as $column => $field)
{
// make sure the column exists
if (array_key_exists($column, $rowData))
{
// store the column data as a property of the row (named per the first row)
$row->$field = $rowData[$column];
}
}
// store the row
$this->rows[$i - 1] = $row;
}
}
// this (along with implements IteratorAggregate) lets us use a foreach statement on the CSV object
public function getIterator()
{
return new ArrayIterator($this->rows);
}
// example of the extra functionality we can add to the object
public function getRow($num)
{
return $this->rows[$num];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment