1. 程式人生 > >利用Iterator讀取cvs檔案

利用Iterator讀取cvs檔案

平時讀取csv檔案都是用while迴圈,最近在看文件時發現一個新方法:利用iterator


<?php

namespace demo\test;

use Iterator;

class CsvFileIterator implements Iterator
{
    private $file;
    private $key = 0;
    private $current;

    public function __construct($file)
    {
        $this->file = fopen($file, 'r');
    }

    public function __destruct()
    {
        fclose($this->file);
    }

    public function current()
    {
        return $this->current;
    }

    public function next()
    {
        $this->current = fgetcsv($this->file);
        $this->key++;
    }

    public function key()
    {
        return $this->key;
    }

    public function valid()
    {
        return !feof($this->file);
    }

    public function rewind()
    {
        rewind($this->file);
        $this->current = fgetcsv($this->file);
        $this->key = 0;
    }
}

使用方法

$lines = new CsvFileIterator('test.csv');
foreach ($lines as $key => $line) {
    var_dump($key, $line);
}

原理都一樣,只是換了個方式