PHP Write File - Write to File in PHP

In this tutorial we will learn how to write to files in PHP. Writing to files in PHP is the next step after we know how to open a file in PHP.

This tutorial takes us through writing to files in PHP and will teach how to actually save some data to a file on the server.

We write to a file using the appropriately named fwrite function. Have a look at the tutorial below which explains how to write to a file in PHP.

PHP fwrite Syntax

The syntax for the fwrite function is shown below:

fwrite($fileHandle, $dataToWrite);

Once again, $fileHandle is a variable to tell PHP the particular file we will be writing to. The $fileHandle variable will come from our fopen function since we have to open a file before we can do anything to it. $dataToWrite is a variable that contains the data that we want to write to the file.

PHP fwrite Example - Writing to a file in PHP

The code below shows how to write to a file in PHP:

<?php
 
$file = "test.txt";
$fileHandle = fopen($file, 'w') or die("Error opening file");
 
$data = "Tutorial Arena rocks\n"; // set data we will be writing
fwrite($fileHandle, $data); // write data to file 
 
$data = "I just love it\n";
fwrite($fileHandle, $data);
 
fclose($fileHandle); // close the file since we're done
 
?>

The contents of "test.txt" will be:

Tutorial Arena rocks
I just love it

Note the newline (\n) characters that were used in the code. These were to ensure that each set of data was written in a new line.

Since we are using write mode, continuously running the script will not keep adding lines to the file. This is because in write mode, the pointer is placed at the beginning of the file, effectively erasing its contents each time.

PHP fwrite Append Example - Writing to a file in PHP in Append Mode

The code below would write new data to the end of the file instead:

<?php
 
$file = "test.txt";
$fileHandle = fopen($file, 'a'); // Note that the mode has changed
 
$data = "Tutorial Arena rocks\n"; // set data we will be writing
fwrite($fileHandle, $data); // write data to file 
 
$data = "I just love it\n";
fwrite($fileHandle, $data);
 
fclose($fileHandle); // close the file since we're done
 
?>

If you were to run this code more than once, you would see that the size of the file would keep increasing since more lines would be added to the end of it. Changing the mode to append makes all the difference. That is all there is to using PHP to write to a file.

Remember that once finished with a file, it is a good idea to close the file to prevent any resource conflicts.

We hope this tutorial on writing to files in PHP was useful.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...