FileIterator.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * User: dongdx
  4. * Date: 2017/9/5
  5. * Time: 16:23
  6. */
  7. namespace PhpLife\Library;
  8. class FileIterator extends \IteratorIterator
  9. {
  10. private $fp;
  11. private $index = 0;
  12. private $line;
  13. public function __construct($filename)
  14. {
  15. $fp = fopen($filename, "r");
  16. if (!$fp) {
  17. die("can't open this file");
  18. }
  19. $this->fp = $fp;
  20. $this->line = rtrim(fgets($this->fp), "\n");
  21. }
  22. public function rewind()
  23. {
  24. $this->index = 0;
  25. rewind($this->fp);
  26. $this->line = rtrim(fgets($this->fp), "\n");
  27. }
  28. public function next()
  29. {
  30. $this->index++;
  31. $this->line = rtrim(fgets($this->fp), "\n");
  32. if (!feof($this->fp)) {
  33. return $this->line;
  34. } else {
  35. return null;
  36. }
  37. }
  38. public function key()
  39. {
  40. return $this->index;
  41. }
  42. public function current()
  43. {
  44. return $this->line;
  45. }
  46. public function valid()
  47. {
  48. return feof($this->fp) ? false : true;
  49. }
  50. }