Skip to content

Instantly share code, notes, and snippets.

@yuya-takeyama
Created September 30, 2010 16:23
Show Gist options
  • Save yuya-takeyama/604863 to your computer and use it in GitHub Desktop.
Save yuya-takeyama/604863 to your computer and use it in GitHub Desktop.
An easy example of IteratorAggregate implementation.
<?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;
}
}
foo bar baz
hoge fuga piyo
<?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