php - file write
Now that you know how to open and close
a file, lets get on to the most useful part of file manipulation, writing!
There is really only one main function that is used to write and it's logically
called fwrite.
php - file open: write
Before we can write information to our test file we have to use
the functionfopen to open
the file for writing.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
We can use php to write to a text file. The fwrite function allows data to be written to
any type of file. 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 carriaged
return.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't
open file");
$stringData = "Bobby
Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy
Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
We wrote to the file testFile.txt twice. Each time we wrote to the file
we sent the string $stringData that first contained Bobby Bopper and second containedTracy Tanner.
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:
php - file write: overwriting
Now that 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:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\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.
Comments
Post a Comment
Thank you for your Comment