某度早期php简易面试题,用php处理大容量文件,比如内存只有100m,要处理2G的文本文件,php怎么办?
可以通过fgets函数来逐行读取,然后通过Iterator来实现一个迭代器,方便遍历,
分享下代码:
<?php
class Reader implements Iterator {
private $num;
private $handler;
public function __construct($file)
{
$this->handler = fopen($file, "r");
}
public function __destruct()
{
fclose($this->handler);
}
public function current()
{
return fgets($this->handler, 2048);
}
public function next()
{
$this->num++;
}
public function key()
{
return $this->num;
}
public function valid()
{
return !feof($this->handler);
}
public function rewind()
{
fseek($this->handler, 0);
$this->num = 1;
}
}
$file = __FILE__;
$reader = new Reader($file);
foreach ($reader as $k => $v) {
echo $k ."\t\t" . $v . "\r\n";
}