首页 > 开发 > PHP > 正文

php遍历CSV类实例

2024-05-04 23:34:10
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了php遍历CSV类,实例分析了php针对csv文件的打开、读取及遍历的技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了php遍历CSV类。分享给大家供大家参考。具体如下:

 

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

希望本文所述对大家的php程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表