Next, let’s take a look at how to write to a file! The process of writing to a file is similar to reading, except we use the fopen
function to open a file in write mode:
$file = fopen("hello.txt", "w");
This opens hello.txt
in write mode (w
), assigning the file pointer to a new variable called $file
. When opening a file in write mode, fopen
will work in one of two ways:
- If the file being opened does not exist in the current directory, the file will be created.
- If the file being opened does exist already, any existing content in the file will be deleted. If this isn’t what we want, we can also append to a file without erasing what’s already there — we’ll learn how in the next exercise.
For this example, let’s assume that hello.txt
did not already exist. By opening the file in write mode, we created an empty file called hello.txt
. We can then write to the file using the fwrite
function:
fwrite($file, "Hello, world!");
fwrite
works by taking two arguments. The first argument is $file
, the file pointer we opened for hello.txt
. The second argument is the text we’d like to write: “Hello, world!”. This will write “Hello, world!” to hello.txt
.
As long as the file pointer is open, we can call fwrite
as many times as we’d like. To add text on a new line, indicate the line break with a \n
:
fwrite($file, "\n" . "This will be on a new line.");
Now, the directory where we created our PHP script contains a file, hello.txt
, with the text we wrote:
Hello, world! This will be on a new line.
As always, we’ll need to close the file when we’re finished:
fclose($file);
Now, let’s practice writing to a file!
Instructions
Open my-bands.txt
in write mode, storing the file pointer in a variable called $bands_file
.
Use the fwrite
function to write the name of a musical band you like to my-bands.txt.
Check out your new file, my-bands.txt
! When you are finished, close the file.