Created
August 16, 2012 08:57
-
-
Save amitayh/3368519 to your computer and use it in GitHub Desktop.
PHP file iterator
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 CsvIterator extends FileIterator | |
{ | |
/** | |
* @var string | |
*/ | |
protected $_delimiter; | |
/** | |
* @var string | |
*/ | |
protected $_enclosure; | |
/** | |
* @param string $filename | |
* @param string $delimiter | |
* @param string $enclosure | |
*/ | |
public function __construct($filename, $delimiter = ',', $enclosure = '"') { | |
parent::__construct($filename); | |
$this->_delimiter = $delimiter; | |
$this->_enclosure = $enclosure; | |
} | |
protected function _getNextRow() { | |
return fgetcsv($this->_handle, null, $this->_delimiter, $this->_enclosure); | |
} | |
} |
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 FileIterator implements Iterator | |
{ | |
/** | |
* @var resource | |
*/ | |
protected $_handle; | |
/** | |
* @var int | |
*/ | |
protected $_key; | |
/** | |
* @var mixed | |
*/ | |
protected $_row; | |
/** | |
* @param string $filename | |
*/ | |
public function __construct($filename) { | |
if (($this->_handle = @fopen($filename, 'r')) === false) { | |
throw new Exception('Unable to open file handle'); | |
} | |
} | |
public function __destruct() { | |
fclose($this->_handle); | |
} | |
public function current() { | |
return $this->_row; | |
} | |
public function next() { | |
$this->_key++; | |
} | |
public function key() { | |
return $this->_key; | |
} | |
public function valid() { | |
$this->_row = $this->_getNextRow(); | |
return ($this->_row !== false); | |
} | |
public function rewind() { | |
rewind($this->_handle); | |
$this->_key = 0; | |
} | |
protected function _getNextRow() { | |
return fgets($this->_handle); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment