Created
October 11, 2015 10:36
-
-
Save ronisaha/c0649f5a3d9707fc0a29 to your computer and use it in GitHub Desktop.
EasyCSVIterator
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 EasyCSVIterator implements \Iterator { | |
| protected $file; | |
| protected $key = 0; | |
| protected $current; | |
| protected $header; | |
| protected $hasHeader; | |
| public function __construct($file, $hasHeader = false) { | |
| $this->file = fopen($file, 'r'); | |
| $this->hasHeader = $hasHeader; | |
| $this->readHeader(); | |
| $this->readCsvLine(); | |
| } | |
| public function __destruct() { | |
| fclose($this->file); | |
| } | |
| public function rewind() { | |
| if($this->key == 0) { | |
| return; | |
| } | |
| rewind($this->file); | |
| if($this->hasHeader()) { | |
| $this->header = $this->getCsvRow(); | |
| } | |
| $this->readCsvLine(); | |
| $this->key = 0; | |
| } | |
| public function valid() { | |
| return !feof($this->file); | |
| } | |
| public function key() { | |
| return $this->key; | |
| } | |
| public function current() { | |
| return $this->current; | |
| } | |
| public function next() { | |
| $this->readCsvLine(); | |
| $this->key++; | |
| } | |
| public function hasHeader() { | |
| return $this->hasHeader; | |
| } | |
| /** | |
| * @return array | |
| */ | |
| private function readCsvLine() | |
| { | |
| $csvRow = $this->getCsvRow(); | |
| if($csvRow) { | |
| $this->current = $this->hasHeader() ? array_combine($this->header, $csvRow) : $csvRow; | |
| } | |
| } | |
| /** | |
| * @return array | |
| */ | |
| private function getCsvRow() | |
| { | |
| return fgetcsv($this->file); | |
| } | |
| private function readHeader() | |
| { | |
| if ($this->hasHeader()) { | |
| $this->header = $this->getCsvRow(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment