|
|
| READ TEXTFILES IN PHP |
|
When you want to store some data, either how many viewers your page have registered,
or you want to make a simple guestbook, you have to store the data. Textfiles is
a rather easy way to do this. In this tutorial I will show how to read and manipulate
some data from the textfile.
|
The Textfile
|
|
I have called this textfile, apron.txt. It is a textfile with the content below:
|
This is the first textfile I will read.
Php has simple methods to read from textfiles.
Is it easy? make your own cool project with textfiles
and php, and submit it in apron guest developer
section. This is a nice way to show your work.
It is your creativity that result in the project's
quality.
|
Get the content of the textfile
|
|
In order to get the content of the textfile, you have to open it,
and then read it. Under we set the content to a variable, close the file
and then write it out.
|
|
Show Script In Action
|
//give the name to the file
$filename = "apron.txt";
//open file
$fileToOpen = fopen($filename,"r");
//set the content of the file into a variable
$content = fread($fileToOpen, filesize($filename));
//close the file
fclose($fileToOpen);
//write the content
echo($content);
|
|
As you can se in the example above the linebreaks from the textfile does not
appear. In order to do this we use the n12br method as below:
|
|
Show Script In Action
|
//give the name to the file
$filename = "apron.txt";
//open file
$fileToOpen = fopen($filename,"r");
//set the content of the file into a variable
$content = fread($fileToOpen, filesize($filename));
//set line break
$content = nl2br($content);
//close the file
fclose($fileToOpen);
//write the content
echo($content);
|
Get a specific part of the textfile
|
|
If you want to get a specific part of the textfile, you
can use string methods on the $content string.
But if this is neccesary I recommend that you use a
xml files or a database to store your data in. I have made some
methods for this in the wrapper class for textfile. You get get
this class and read more about it here.
|
|
Category
|
Programming with PHP
|
|
Author
|
Tommy Johannessen
|
|
|
|