tag:blogger.com,1999:blog-16393201611878270912024-03-05T14:47:32.831-08:00PHP Dev ZonePersonal Archive of Useful Code SnippetsKetan Patelhttp://www.blogger.com/profile/03311967824595948273noreply@blogger.comBlogger1125tag:blogger.com,1999:blog-1639320161187827091.post-67515824499722488412014-05-03T07:32:00.000-07:002014-05-03T07:32:03.820-07:00How to write to a file in phpIn 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 <b>fwrite()</b> function of PHP.<br />
<br />
But before to start writing anything in a file you must be clear with the flow.Complete logic would be like this.<br />
<br />
• You have to read the file.<br />
• Then write the data you want to write.<br />
• Close the file after adding data.<br />
<div>
<br /></div>
Now lets understand the logic in detail.As the first step is to open the file, we will use <b>fopen()</b> function.To open a file you have declare the path of the file.<br />
<div>
<br /></div>
<div>
<h4>
Example :</h4>
<div>
<code>
$filepath = 'testfile.txt';</code><br />
<code>$fp = fopen($filepath,'w');</code></div>
</div>
<div>
<br /></div>
<div>
<div>
You might thinking of the second parameter passed in the function. A list of some other parameters is as below.</div>
<div>
<br /></div>
<div>
<b>r</b> = Read only. Will be started from the beginning of the file.</div>
<div>
<b>w </b>= Write only. New file will be created if it doesn't exist and previously written data will be erased.</div>
<div>
<b>a </b>= 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.</div>
<div>
<b>x</b> = Create a new file. If the specified file already exists then it returns false and throws error. </div>
</div>
<div>
<br /></div>
<div>
<div>
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.</div>
<div>
<br /></div>
<div>
<code>
fwrite($fp,” This is Sample Text”);</code></div>
<div>
<br /></div>
<div>
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.</div>
<div>
<br /></div>
<div>
<code>
fclose($fp);</code></div>
<div>
<br /></div>
<div>
Now open the testfile.txt and you’ll see the data entered in it.</div>
<div>
<br /></div>
<div>
<b>Complete Code to write the data to a text file.</b></div>
<div>
<br /></div>
<div>
<code>
$data = "This is Sample Text"; //Your sample data</code><br />
<code>$file = 'testfile.txt'; //File path</code><br />
<code>$fp = fopen($file, 'w'); //Opening file</code><br />
<code>fwrite($fp, $data); //Writing the data</code><br />
<code>fclose($fp); //Closing file</code></div>
</div>
<div>
<br /></div>
Ketan Patelhttp://www.blogger.com/profile/03311967824595948273noreply@blogger.com0