Write text into a text file with PHP

Posted by Shek on May 23, 2008 under PHP | Be the First to Comment | Total View: 285 views

Database is to store data for future use, however we could also store string in a text file for future use. The way to do this is very simple, all we have to do is to use the PHP function fwrite() to write the string into the text file. I have created an example here to demonstrate how to do so.

I have created a PHP file named “text.php” and an empty text file named “atextfile.txt”. Both files have uploaded into the same directory.

To be able to write into the text file “atextfile.txt”, we have to set the file permission of “atextfile.txt” to “777″ in order for it to be writable. This process can be done with most of the FTP softwares.

Now here are the codes of the “text.php” file:

First we create a PHP variable to store the full name of the text file:

$tempfile="atextfile.txt";

We now use the PHP function fopen() to open the text file and make it ready to write, “w” is to set the text file to write only.

$fileprocess=fopen($tempfile,"w");

We then create the text which we like to write it into the text file. We use a PHP variable to store the text.

$temptext = "hello world!";

Here we use the the PHP function fwrite() to write the text into the text file:

fwrite($fileprocess,$temptext);

At last we close the file:

fclose($fileprocess);

All together we have:

1
2
3
4
5
6
7
<?php
$tempfile="atextfile.txt";
$fileprocess=fopen($tempfile,"w");
$temptext = "hello world!";
fwrite($fileprocess,$temptext); 
fclose($fileprocess);
?>

In this example, we can only write a line of text into the text file.
All text within the text file will be overwritten.

Similar Posts:

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Add A Comment

*