Writing to a File

To write a file in PHP, there are a couple of very simple steps. We are going to create a text file called testing.txt and write to it using PHP.

Step 1

$file_name = "testing.txt";
$fh = fopen($file_name, 'w');

In the first part, we simply specify the name of the file that we want to open and assign it to the variable $file_name. On the second line, we call the PHP function fopen and pass 2 parameters. The first parameter is the name of the file, and the second parameter specifies the mode we are opening the file in. In our case, we are opening a new file for write and we use ‘w’

Step 2

$fruits = "apple\n";
$fruits .= "banana\n";
$fruits .= "orange";
fwrite($fh, $fruits);

The first 3 lines assign the names of 3 fruits, with line breaks in between to a variable named $fruits. The fwrite functions is then used to write that information to a file. The first argument passed to the fwrite function is the file handle. Basically, its the variable name that we assigned when we originally opened the file. In our case, that’s $fh. The second argument is the string with the data that you want to put in the file.

Full Code

$file_name = "testing.txt";
$fh = fopen($file_name, 'w');

$fruits = "apple\n";
$fruits .= "banana\n";
$fruits .= "orange";
fwrite($fh, $fruits);

fclose($fh);
Posted by Will on November 12, 2012

Leave a Reply

Your email address will not be published. Required fields are marked *