PHP File Manipulation Writing to a File Tutorial

Find out how to write data to a flat file database (text document) using this tutorial.

PHP File Manipulation Writing to a File Tutorial

File Manipulation in PHP

     

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"; 0

fputs($file,$str);

$file=fopen("Newest.txt","r");

while(!feof($file)) 1

{

  echo fgets($file)."<br/>";

} 2

?>

Output:

This is same file with different textThis is same file with extra text which has been appended 3

Note: For further details please visit our web page: http://roseindia.net/tutorial/php/phpbasics/tutorial/PHP-File-Handling.html