In the previous exercise, we learned that we can write to a file by opening it in write mode (
w). When a file is opened in write mode, any existing content is deleted. Sometimes, we’ll prefer this behavior. However, other times, we’ll want to add to an existing file without erasing what’s already there. This process is known as appending. We can append in PHP by opening the file in append mode:
$file = fopen("hello.txt", "a");
hello.txt with the
fopen function, using
"a" as the second argument to open the file in append mode. Unlike write mode, this tells PHP to preserve any existing content as it opens the file. However, if the file does not exist yet, PHP will still create the file.
Let’s see it in action using our above file
hello.txt with the following content:
Once we’ve opened the file, we’ll still use the
fwrite function to write to the file. Let’s try it out:
fwrite($file, " Let’s learn PHP file handling!");
Since we opened the file in append mode, this writes to the end of the file without modifying what’s already there. If we looked at
hello.txt now, we would see this:
Hello, world! Let’s learn PHP file handling!
To practice using append mode, let’s try appending to a file ourselves!
We’ve got a file,
cool-pets.txt, that’s supposed to list our favorite pets. We forgot someone while creating this list, so let’s add them to the list now.
To start, open up the
cool-pets.txt file in append mode and assign the file pointer to
Add the name of your favorite pet to the file.
cool-pets.txt to make sure your new pet was added. When you’re finished, go ahead and close the file we were working with.