首頁 >後端開發 >php教程 >php遍歷CSV的方法 php遍歷csv的類

php遍歷CSV的方法 php遍歷csv的類

WBOY
WBOY原創
2016-07-25 08:56:151016瀏覽
  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. ?>
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn