PHP: Create a New Text File & Write Content to it
In this tutorial, we will learn how to create a text file in PHP and write some content to it.
Create a File
The first step is to open the file you wish to create using the PHP
fopen() function and store the result in a variable:
$list = fopen('list.txt', "w");
The first argument is the path to the file to create and the second is the mode, which is
Writing Content to the File
Now we can write content to the file using the PHP
fwrite() function. The first argument is the file object we previously created and the second is the content to add.
fwrite($list, 'Some content.');
Closing the File
The file must be closed at some point in your program to stop it eating memory. This is done using the
fclose() function and passing the file object as the first argument.
Here is the full example of creating a file, adding content to it then closing the file:
$list = fopen('list.txt', "w"); fwrite($list, 'Some content.'); fclose($list);