green php elephants - elephpantsJust a simple code snippet to remind myself just how easy it is to spit out content into a text file using PHP.

As you can see from the code snippet below, to write data to a text file in PHP we make use of three functions, namely fopen, fwrite and fclose.

As its name implies, fopen is responsible for opening the stream. Note the use of the ‘w’ switch which indicates we are opening a stream for writing. This will also force the creation of the file if it doesn’t exist.

The fwrite is used to insert text into the stream and finally the fclose essentially saves the changes and closed the handle opened initially by the fopen call.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, "Text sentence for line 1n");
fwrite($fh, "Text sentence for line 2n");
fclose($fh);

Note, if you wish to append data to an existing file, simply use the fopen function with an ‘a’ switch.

This is demonstrated below:

if (is_writable($myFile)) {
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "Appended text sentence for line 1n");
fwrite($fh, "Appended text sentence for line 2n");
fclose($fh);
}

Simple isn’t it? Don’t know why I keep forgetting it then! O.o