Posted By

koncept on 01/16/07


Tagged

php5 iterator csv


Versions (?)

Who likes this?

17 people have marked this snippet as a favorite

tylerhall
reiko
basicmagic
halbtuerke
WimLeers
vali29
sumandahal
Anber
irishsk
nb109
sultano
FazzyX
tikitakfire
kaartz
ringo380
tux-world
vp_arth


PHP5 CSV Iterator


 / 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!

  1. <?php
  2. class CSVIterator implements Iterator
  3. {
  4. const ROW_SIZE = 4096;
  5.  
  6. private $filePointer;
  7. private $currentElement;
  8. private $rowCounter;
  9. private $delimiter;
  10.  
  11. public function __construct( $file, $delimiter = ',' )
  12. {
  13. $this->filePointer = fopen( $file, 'r' );
  14. $this->delimiter = $delimiter;
  15. }
  16.  
  17. public function rewind()
  18. {
  19. $this->rowCounter = 0;
  20. rewind( $this->filePointer );
  21. }
  22.  
  23. public function current()
  24. {
  25. $this->currentElement = fgetcsv( $this->filePointer, self::ROW_SIZE, $this->delimiter );
  26. $this->rowCounter++;
  27. return $this->currentElement;
  28. }
  29.  
  30. public function key()
  31. {
  32. return $this->rowCounter;
  33. }
  34.  
  35. public function next()
  36. {
  37. return !feof( $this->filePointer );
  38. }
  39.  
  40. public function valid()
  41. {
  42. if( !$this->next() )
  43. {
  44. fclose( $this->filePointer );
  45. return FALSE;
  46. }
  47. return TRUE;
  48. }
  49.  
  50. } // end class
  51. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: tylerhall on January 16, 2007

That's the best code snippet I've seen in a long time. I can't even begin to describe how useful this is. :)

Posted By: rhalff on August 28, 2009

Make sure autodetectline_endings is set to true! This will auto guess the line ending, very usefull.

iniset('autodetectlineendings', true);

Posted By: tidal on February 5, 2010

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.

You need to login to post a comment.