In this tutorial we will learn how to write data to a flat file database (text document) using this tutorial.
In PHP, we can do many things with file, like creation of file, update of file, deletion of file etc. One of the important work is writing to a file, following example will illustrate how to open a file and write into it, in addition we will learn how to open a file and read the The following examples will let you know about the most basic form of file handling.
Example 1 (Let's assume that we have created a .txt file inside C:\wamp\www\php directory, where we will write the .php file):
<?php
$file=fopen("Newest.txt","r"); while(!feof($file))
{
echo (fgets($file));}
?>
Output:
In PHP, we can do many things with file, like creation of file, update of file, deletion of file etc. One of the important work is writing to a file, following example will illustrate how to open a file and write into it. In addition we will learn how to open a file and read the The following examples will let you know about the most basic form of file handling.
Example 2 (If you want to create the file, we will use 'w' mode instead of 'r'):
<?php
$file=fopen("Newest.txt","w"); $str="This is same file with different text";
fputs(
$file,$str); $file=fopen("Newest.txt","r"); while(!feof($file)){
echo fgets($file)."<br/>";}
?>
Output:
This is same file with different text
Example 3 (If you want to append some text into a file change the mode into 'a'):
<?php
$file=fopen("Newest.txt","a"); $str="This is same file with extra text which has been appended";
fputs(
$file,$str); $file=fopen("Newest.txt","r"); while(!feof($file)){
echo fgets($file)."<br/>";}
?>
Output:
This is same file with different textThis is same file with extra text which has been appended
Note: For further details please visit our web page: http://roseindia.net/tutorial/php/phpbasics/tutorial/PHP-File-Handling.html
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: PHP File Manipulation Writing to a File Tutorial
Post your Comment