0% found this document useful (0 votes)
40 views

PHP Tizag Tutorial-60

The document discusses how to write to files in PHP. It explains that the fwrite function allows writing data to any file type, with the file handle and string as parameters. Code examples show opening a file for writing, using fwrite to add two names separated by a carriage return, and closing the file. If opened, the test file would contain the two written names.

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

PHP Tizag Tutorial-60

The document discusses how to write to files in PHP. It explains that the fwrite function allows writing data to any file type, with the file handle and string as parameters. Code examples show opening a file for writing, using fwrite to add two names separated by a carriage return, and closing the file. If opened, the test file would contain the two written names.

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

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 function fopen to open the file for
writing.

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

PHP - File Write: fwrite Function

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);

The $fh variable contains 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 Bobby Bopper and second contained Tracy 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:

Contents of the testFile.txt File:


Bobby Bopper
Tracy Tanner

You might also like