Home  >  Article  >  Backend Development  >  php method to traverse CSV php class to traverse csv

php method to traverse CSV php class to traverse csv

WBOY
WBOYOriginal
2016-07-25 08:56:15955browse
  1. /**
  2. * Traverse csv files
  3. * edit: bbs.it-home.org
  4. */
  5. class CSVIterator implements Iterator
  6. {
  7. const ROW_SIZE = 4096;
  8. private $filePointer;
  9. private $currentElement;
  10. private $rowCounter;
  11. private $delimiter;
  12. public function __construct( $file, $delimiter = ',' )
  13. {
  14. $this->filePointer = fopen( $file, 'r' );
  15. $this->delimiter = $delimiter;
  16. }
  17. public function rewind()
  18. {
  19. $this->rowCounter = 0;
  20. rewind( $this->filePointer );
  21. }
  22. public function current()
  23. {
  24. $this->currentElement = fgetcsv( $this->filePointer, self::ROW_SIZE, $this->delimiter );
  25. $this->rowCounter++;
  26. return $this->currentElement;
  27. }
  28. public function key()
  29. {
  30. return $this->rowCounter;
  31. }
  32. public function next()
  33. {
  34. return !feof( $this->filePointer );
  35. }
  36. public function valid()
  37. {
  38. if( !$this->next() )
  39. {
  40. fclose( $this->filePointer );
  41. return FALSE;
  42. }
  43. return TRUE;
  44. }
  45. } // end class
  46. ?>
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn