Last active
November 25, 2015 11:22
-
-
Save wallacemaxters/d422dde3fdc299d90ef1 to your computer and use it in GitHub Desktop.
A little csv reader class for php
This file contains 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 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