TxtFile – PHP Library to Read/Write Text File

TxtFile is a small library to help read and write to text file.

Install and create object to handle a file

composer require tltemplates/txtfile
//access the file
$file = new TxtFile('myfile.txt'); 
//access the file and create if it does not exist
$file = new TxtFile('myfile.txt', true); 

Read file

//read the whole file store result in an array
$content = $file->readAllAsArray();

//read the whole file store result in a string
$content = $file->readAllAsString();

//read first 10 lines
$content = $file->readAsString(0, 9);
$content = $file->readAsArray(0, 9);

//read all and remove blank lines
$content = $file->readAllWithoutBlankLines();

//read all and remove duplicated lines
$content = $file->readAllWithoutDuplicatedLines();

Write to file

//write to end of file
$file->writeAt(100000, $text); //use any number which exceeds total lines of the file's content

//write to certain line
$file->writeAt(0, $text);
//writeLineAt is similar to writeAt but it automatically appends line break at the end of $text
$file->writeLineAt(10, $text); 

//empty file's content

Leave a Comment

Your email address will not be published.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.