In the last tutorial we studied how to open and read files in PHP. This tutorial will explain the process of doing the reverse i.e. creating a file and writing data to it. So without wasting any time further, let’s have a look at our first example.
You will be surprised to see that the fopen function is also used for creating the files. If the file name passed as the parameter to the fopen function doenst exist, the fopen function creates it. However, it is imperative that the second parameter should be either ‘w’ or ‘a’. Once the file is opened, you simply have to pass the use fwrite function to write the contents into the file. The first parameter of the fwrite function takes the file in which the content is to be written, and the second parameter is the text to be written. The file will be created in the same directory where the PHP script exists.
It is important to know that whenever fopen function is used with ‘w’ flag, all the contents in the already existing file would be erased and the new content will be written to the file. To append the content to already existing file use ‘a’ flag as second parameter inside the fopen function. Have a look at second example to see how append works.
If the above code is executed, a line of text will be appended at the end of the myfile.txt file created in the last example.