We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

koncept on 01/16/07


Tagged

php5 iterator csv


Versions (?)


Who likes this?

7 people have marked this snippet as a favorite

tylerhall
reiko
basicmagic
halbtuerke
WimLeers
vali29
sumandahal


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. :)

You need to login to post a comment.