/ Published in: PHP
I think I got this one off php.net. I wish I could thank the author properly because this has been a real helper!
Expand |
Embed | Plain Text
<?php class CSVIterator implements Iterator { const ROW_SIZE = 4096; private $filePointer; private $currentElement; private $rowCounter; private $delimiter; public function __construct( $file, $delimiter = ',' ) { $this->delimiter = $delimiter; } { $this->rowCounter = 0; } { $this->rowCounter++; return $this->currentElement; } { return $this->rowCounter; } { } public function valid() { if( !$this->next() ) { return FALSE; } return TRUE; } } // end class ?>
Comments
Subscribe to comments
You need to login to post a comment.

That's the best code snippet I've seen in a long time. I can't even begin to describe how useful this is. :)
Make sure autodetectline_endings is set to true! This will auto guess the line ending, very usefull.
iniset('autodetectlineendings', true);
hmm, for sure the above CSVIterator class implements the Iterator Interface, but it does not what an Iterator is expected to do: The "current" method should allways return the current entry of whatever an Iterator is iterating over. Instead this class` "current" method returns allways the next entry - So it returns actually an $iterator->next(); $iterator->current(). On the other hand it´s "next" method does what the "valid" method is expected to do - Checking if there is (atleast) one more entry and not moving to the next entry.
There is a native PHP class "SplFileObject" which also implements Iterator and does what it should do and it has a "fgetcsv" method which returns the current line split by a delimiter.