Skip to content
//-->

June 23, 2010

TextFile Class for PHP

The following class is plays a big part in the framework I use for each of my web sites.  It wraps around PHP’s default functions for handling files.  It is specifically made to deal with text files.  Its main feature is to create separate states for dealing with text files–a file starts out as unopened, can then be opened, closed, and deleted. You can download it here, or click “Read More” for some documentation. 

Here is an example on how to use the textfile class:

$loTextFile = new TextFile("test.txt");
if (!$loTextFile->fileExists())
{
	echo "The text file does not exist!<br />";
	$loTextFile->createFile();
	echo "Creating text file " . $loTextFile->getFileName() . "<br />";
}
 
if ($loTextFile->fileExists())
{
	echo "File exists!<br />";
}
 
if (!$loTextFile->isFileOpened())
{
	echo "The file is not opened!<br />";
	$loTextFile->openFile();
	echo "Opening text file " . $loTextFile->getFileName() . "<br />";
}
 
if ($loTextFile->isFileOpened())
{
	echo "Text file output: " . $loTextFile->readFile() . "<br />";
	echo "Writing data to text file " . $loTextFile->getFileName() . "<br />";
	$loTextFile->writeToFile("Line 1<br />");
	echo $loTextFile->readFile() . "<br />";
	echo "Appending to text file " . $loTextFile->getFileName() . "<br />";
	echo $loTextFile->appendToFile("Line 2<br />");
	echo $loTextFile->readFile() . "<br />";
	echo "Prepending to text file " . $loTextFile->getFileName() . "<br />";
	echo $loTextFile->prependToFile("Line 0<br />");
	echo $loTextFile->readFile() . "<br />";
	echo "Deleting text file " . $loTextFile->getFileName() . "<br />";
	$loTextFile->deleteFile();
}
 
if ($loTextFile->isFileDeleted())
{
	echo "Cannot modify text file because it is deleted!<br />";
}

Your output should look like this:

The text file does not exist!
Creating text file test.txt
File exists!Text file output:
Writing data to text file test.txt
Line 1

Appending to text file test.txt
Line 1
Line 2

Prepending to text file test.txt
Line 0
Line 1
Line 2

Deleting text file test.txt
Cannot modify text file because it is deleted!

The demo can be viewed here.

Read more from Projects

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments