PHP Programing language

adplus-dvertising
PHP Write
Previous Home Next

Before we can write information to our test file we have to use the function fopen to open the file for writing.

PHP Code:

<?php
$File = "testFile.txt";
$fh = fopen($File, 'w');
?>

Implementation of fwrite() Function

In php to write to a text file. and implement the fwrite function allows data to be written to any type of file. The Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written.

Just give the function those two bits of information and you're good to go.

Below we are writing a couple of names into our test file testFile.txt and separating them with a carriage return.

PHP Code:

<?php
$myFile = "testFile.txt";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = "Amit\n";
fwrite($fh, $stringData);
$stringData = "Akash\n";
fwrite($fh, $stringData);
fclose($fh);
?>

The $fh variable containing the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Amit and second contained Akash. After we finished writing we closed the file using the fclose function.

If you were to open the testFile.txt file in NOTEPAD it would look like this:

Contents of the testFile.txt File:
Amit
Akash

How to Overwriting in PHP

testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing file testFile.txt and write some new data into it.

PHP Code:

<?php
$myFile = "testFile.txt";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = "Akash\n";
fwrite($fh, $stringData);
$stringData = "Anik\n";
fwrite($fh, $stringData);
fclose($fh);
?>

If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present. Contents of the testFile.txt File:

Akash 
Anik

In the next lesson we will show you how to get information out of a file by using PHP's read data functions!

Previous Home Next