PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

HOW TO WRITE TO FILES USING THE fwrite() FUNCTION IN PHP

To write data to file, you use the fwrite() function on PHP. You will need to open the file first in write mode before any writing can take place. It takes two arguments, the file handle and the actual data to write. The data to write can be a string or a variable.

The general format is:

fread(filehandle, data_to_write);

Example 1:

<?

$myFile="test.txt";
$fd=fopen($myFile, "w");
fwrite($fd, "My name is Dan Stern.");
fclose($fd);

?>

Example 2:

<?

$myFile="test.txt";
$data="My friend called today.";
$fd=fopen($myFile, "w");
fwrite($fd, $data);
fclose($fd);

?>

First, we use the fopen function to open the file in write mode. If the file doesn't exist, PHP creates it in the same directory as the fwrite script. Then we use the fwrite function to write the data to file. We then close the file using the fclose function. $contents variable then holds the contents of the file.

Note that fwrite completely erases the file before it writes to it. If you want to add additional data to end of file without erasing the original contents, then use the append mode as follows:

Example

<?

$myFile="test.txt";
$fd=fopen($myFile, "a");
fwrite($fd, "My name is Dan Stern.");
fclose($fd);

?>

Home | Privacy Policy | Terms Of Use | Contact Us