Created
September 30, 2010 16:23
-
-
Save yuya-takeyama/604863 to your computer and use it in GitHub Desktop.
An easy example of IteratorAggregate implementation.
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 | |
/** | |
* Csv file iterator. | |
* An easy example of IteratorAggregate implementation. | |
* Iteration logics are provided by SplFileObject. | |
* | |
* @author Yuya Takeyama <sign.of.the.wolf.pentagram@gmail.com> | |
*/ | |
class Csv implements IteratorAggregate | |
{ | |
/** | |
* Filename | |
* | |
* @var string | |
*/ | |
protected $_filename; | |
/** | |
* Constructor | |
* | |
* @param array $filename | |
*/ | |
public function __construct($filename) | |
{ | |
$this->_filename = $filename; | |
} | |
/** | |
* Gets iterator object. | |
* | |
* @return SplFileObject | |
*/ | |
public function getIterator() | |
{ | |
$file = new SplFileObject($this->_filename, 'r'); | |
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY | SplFileObject::READ_CSV); | |
return $file; | |
} | |
} |
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
foo | bar | baz | |
---|---|---|---|
hoge | fuga | piyo |
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 | |
require_once './Csv.php'; | |
$csv = new Csv('./example.csv'); | |
foreach ($csv as $line) { | |
var_dump($line); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment