PHP – Class Read Text File

The given PHP Class helps you to read a text file line by line.

It can open text files and perform several types of line oriented operations.

Currently it can read one line at a time, jump to a given line number and count the total number of
lines in the file.

Code Example: Download Example
index.php
<?php
require("textfilereader.class.php");

$filename = "testfile.txt";
$sf = new TextFileReader($filename);
        $sf->seekLine(1);   // Go to line 1
	while (($val = $sf->readLine())!=NULL)
            echo $val."<br/>";

        echo "Total number of lines: ".$sf->countLines();
?>
textfilereader.class.php
<?php
/*
 * Class TextFileReader version 1.0.0
 */

/**
 * This class is used to read lines from regular text files.
 */
class TextFileReader {

    private $fName = "";
    private $FilePointer = 0;

    public function __construct($filename){
        $this->fName = $filename;
    }

    // Reads lines of a text file in order
    public function readLine(){
        if (!$this->fName)
            return NULL;    //File not found

        $file_handle = fopen($this->fName, "rb");
        fseek($file_handle, $this->FilePointer);
        if(!feof($file_handle)){
            $value = fgets($file_handle);
            $this->FilePointer += strlen($value);
            fclose($file_handle);
            return $value;
        }
        else
            return NULL;
    }

    // Seeks to an identified line number
    public function seekLine($lineNumber){
        if (!$this->fName)
            return NULL;    //File not found

        $file_handle = fopen($this->fName, "rb");
        $this->resetFilePointer();
        for($i=0; $i<$lineNumber; $i++)
            $this->FilePointer += strlen(fgets($file_handle));
        return $this->FilePointer;
    }

    // Resets file pointer to the first position of the file
    private function resetFilePointer(){
        $this->FilePointer = 0;
    }

    // Returns number of file lines
    public function countLines(){
        if (!$this->fName)
            return NULL;    //File not found

        $file_handle = fopen($this->fName, "rb");
        $count = 0;
        while(!feof($file_handle)) {
            fgets ($file_handle);
            $count ++;
        }
        fclose($file_handle);
        return $count;
    }
}
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

2 Comments

  1. avatarmohamed abdou

    it is good and easy code iam novice php programer and i understand it thanks

  2. avatarmikerosss

    Great site. A lot of useful information here. I’m sending it to some friends!

Leave a Comment

Your email address will not be published. Required fields are marked *