//***************************************************************
//** title : An efficient iterative and buffered text file reader
//**
//** story : I once wanted to write a web statistics
//** generator based on parsing the entries of
//** access.log of the Apache server. I used
//** file() to get all the lines in an array.
//** It worked. When I uploaded it on some server
//** I got an out of memmory error from the server.
//** Thats because the file was 18mb. I then
//** wrote this class which loads the text file
//** in chunks of 2048 bytes and has a method
//** for returning one line at a time. A line
//** is ended by a newline ('\n').
//**
//** author : Ioannis Cherouvim
//** e-mail : morales@hack.gr
//** date : 2005-03-22
//*******************************************************
class Reader {
var $file;
var $filename;
var $filesize;
var $step = 2048;
var $buffer = "";
var $bytesRead = 0;
var $delimiter = "\n";
//instantiate reader
function Reader($filename) {
$this->filename = $filename;
}
//close file
function close() {
fclose ($this->file);
}
//get next line of text
function readLine() {
while (strpos($this->buffer, $this->delimiter)===false) {
$temp = fread ($this->file, $this->step);
$this->bytesRead += $this->step;
//check if there are more lines in the buffer
function hasMore() {
return ((($this->filesize - $this->bytesRead) > 0) || (strlen($this->buffer) > 0));
}
}
?>
An example use of this class
<?php
$reader = new Reader("hugefile.log");
$reader->open();
while ($reader->hasMore()) {
$entry = $reader->readLine();
echo "$entry<br>";
}
$reader->close();
?>