Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active November 25, 2015 11:22
Show Gist options
  • Save wallacemaxters/d422dde3fdc299d90ef1 to your computer and use it in GitHub Desktop.
Save wallacemaxters/d422dde3fdc299d90ef1 to your computer and use it in GitHub Desktop.
A little csv reader class for php
<?php
class CSVReader implements SeekableIterator
{
const DEFAULT_DELIMITER = ',';
const DEFAULT_ENCLOSURE = '"';
const DEFAULT_ESCAPE = '\\';
protected $file;
protected $header = [];
protected $key = 0;
protected $isAssociative = false;
public function __construct ($file, $associative = false) {
if (! file_exists($file)) {
throw new Exception("{$file} File not found");
}
$this->file = new SplFileObject($file, 'r');
$this->isAssociative = $associative;
$this->rewind();
}
public function setControl(
$delimiter = self::DEFAULT_DELIMITER,
$enclosure = self::DEFAULT_ENCLOSURE,
$escape = self::DEFAULT_ESCAPE
) {
return $this->file->setCsvControl($delimiter, $enclosure, $escape);
}
public function useAsAssociative($associative)
{
$this->isAssociative = $associative;
}
public function current()
{
if ($this->isAssociative == true) {
return $this->combined();
}
return $this->file->fgetcsv();
}
protected function combined()
{
$line = $this->file->fgetcsv();
$header = $this->header;
$combined = [];
$i = 0;
if (count($header) >= count($line)) {
foreach ($header as $key => $value) {
$combined[$value] = isset($line[$key]) ? $line[$key] : NULL;
}
} else {
foreach ($line as $key => $value) {
$index = isset($header[$key]) ? $header[$key] : $i++;
$combined[$index] = $value;
}
}
return $combined;
}
public function key()
{
return $this->file->key();
}
public function next()
{
$this->file->next();
}
public function valid()
{
return $this->file->valid();
}
public function rewind()
{
$this->file->rewind();
if ($this->isAssociative) {
$this->header = array_filter($this->file->fgetcsv());
}
}
/**
* @param int $position
* */
public function seek($position)
{
$this->file->seek($position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment