欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php遍历CSV的方法 php遍历csv的类

程序员文章站 2024-01-07 18:54:28
...
  1. /**
  2. * 遍历csv文件
  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. ?>
复制代码

上一篇:

下一篇: