To write content in a file, we have to open a file first, then we can write to the file, and finally we have to close the file. Let's explain step by step.
First, we open the file using function fopen() that contains two parameters. First parameter is the file name, and second parameter is the mode of opening that is "w" which stands for writing, as we are opening the file to write something in it.
$file = fopen("a.txt", "w") or die("Unable to open file");
Then we write to the file using fwrite() function. This function accepts two parameters. First parameter is the file pointer. Second parameter is the content to write. In our example we are writing to file a.txt.
echo fwrite($file, "Welcome to the World of PHP");
Finally, we are closing the file using fclose() function and by passing the file pointer as the only parameter.
fclose($file);
Here is the full three lines example at a glance.
$file = fopen("a.txt", "w") or die("Unable to open file");
echo fwrite($file, "Welcome to the World of PHP");
fclose($file);
Now, if we want to add content to a file that has content already, then we have to change the operation mode from "w" to "a" which stands for append, as we are adding new content to an existing file. The new content will be added at the end of old content. Here is an example.
$file = fopen("a.txt", "a") or die("Unable to open file");
echo fwrite($file, "PHP is a server-side language");
fclose($file);