利用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);
}

原理都一样,只是换了个方式

猜你喜欢

转载自www.cnblogs.com/caohui/p/9816080.html