PHP5 CSV Iterator


/ Published in: PHP
Save to your folder(s)

I think I got this one off php.net. I wish I could thank the author properly because this has been a real helper!


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. /**
  6.  * Class CSVIterator
  7.  */
  8. class CSVIterator implements Iterator {
  9.  
  10. /** @var false|resource */
  11. private $filePointer;
  12.  
  13. /** @var int */
  14. private $rowCounter;
  15.  
  16. /** @var string */
  17. private $delimiter;
  18.  
  19. /**
  20.   * CSVIterator constructor.
  21.   *
  22.   * @param $file
  23.   * @param string $delimiter
  24.   */
  25. public function __construct($file, $delimiter = ',') {
  26. $this->filePointer = fopen($file, 'rb');
  27. $this->delimiter = $delimiter;
  28. }
  29.  
  30. public function rewind():void {
  31. $this->rowCounter = 0;
  32. rewind($this->filePointer);
  33. }
  34.  
  35. /**
  36.   * Return the current element
  37.   *
  38.   * @link https://php.net/manual/en/iterator.current.php
  39.   * @return mixed Can return any type.
  40.   */
  41. public function current() {
  42. $currentElement = fgetcsv($this->filePointer, 4096, $this->delimiter);
  43. $this->rowCounter++;
  44. return $currentElement;
  45. }
  46.  
  47. /**
  48.   * Return the key of the current element
  49.   *
  50.   * @link https://php.net/manual/en/iterator.key.php
  51.   * @return string|float|int|bool|null scalar on success, or null on failure.
  52.   */
  53. public function key() {
  54. return $this->rowCounter;
  55. }
  56.  
  57. /**
  58.   * Checks if current position is valid
  59.   *
  60.   * @link https://php.net/manual/en/iterator.valid.php
  61.   * @return bool The return value will be casted to boolean and then evaluated.
  62.   * Returns true on success or false on failure.
  63.   */
  64. public function valid():bool {
  65. if (!$this->next()) {
  66. fclose($this->filePointer);
  67. return FALSE;
  68. }
  69. return TRUE;
  70. }
  71.  
  72. /**
  73.   * Move forward to next element
  74.   *
  75.   * @link https://php.net/manual/en/iterator.next.php
  76.   * @return bool
  77.   */
  78. public function next():bool {
  79. return !feof($this->filePointer);
  80. }
  81.  
  82. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.