Saturday 3 May 2014
How to write to a file in php
In this tutorial we'll learn how to write data in a text file using PHP. This can be done very easily.To accomplish this you will have to use fwrite() function of PHP.
But before to start writing anything in a file you must be clear with the flow.Complete logic would be like this.
• You have to read the file.
• Then write the data you want to write.
• Close the file after adding data.
Now lets understand the logic in detail.As the first step is to open the file, we will use fopen() function.To open a file you have declare the path of the file.
But before to start writing anything in a file you must be clear with the flow.Complete logic would be like this.
• You have to read the file.
• Then write the data you want to write.
• Close the file after adding data.
Example :
$filepath = 'testfile.txt';
$fp = fopen($filepath,'w');
You might thinking of the second parameter passed in the function. A list of some other parameters is as below.
r = Read only. Will be started from the beginning of the file.
w = Write only. New file will be created if it doesn't exist and previously written data will be erased.
a = If you want to keep the previously written data then this parameter will be used. It will append the newly typed data to the file.
x = Create a new file. If the specified file already exists then it returns false and throws error.
Lets say we want to write “This is Sample Text” in the file. Now we will write this data to a test.txt file as below.
fwrite($fp,” This is Sample Text”);
The above syntax will write the text in the specified file.Now don’t forget to close the file after writing the data. Use fclose() function to close the file.
fclose($fp);
Now open the testfile.txt and you’ll see the data entered in it.
Complete Code to write the data to a text file.
$data = "This is Sample Text"; //Your sample data
$file = 'testfile.txt'; //File path
$fp = fopen($file, 'w'); //Opening file
fwrite($fp, $data); //Writing the data
fclose($fp); //Closing file
Subscribe to:
Posts
(
Atom
)