Writing to files in PHP

 

When you need to write to files, there are some more functions you can use.The first of these we'll look at is the fwrite() function. (This needs fopen( ) to first to get a file handle.)

In the next script, we'll try to write some text to a file. We'll use the "w" option, as this will create a file for us, if we don't have one with the filename chosen.

<?PHP

$file_handle = fopen("testFile.txt", "w");
$file_contents = "Some test text";

fwrite($file_handle, $file_contents);
fclose($file_handle);
print "file created and written to";

?>

The new line is the blue coloured one. First we ask PHP to open the file and create a file handle:

$file_handle = fopen("testFile.txt", "w");

So we're asking PHP to create a file handle that points to a text file called "testFile.txt". If a file of this name can't be found, then one will be created with this name. After a comma, we've typed "w". This tells PHP that the file will be write only.

The third line is where we write to the file:

fwrite( $file_handle, $file_contents );

In between the round brackets of fwrite( ), we've placed two things: the file we want to write to, and the contents of the file. And, except for closing the file, that's all you need!

To test to see if it works, run the script. Then look in the folder where you saved the script to. There should now be a file called testFile.txt.


Exercise
Change the "w" into "a". Run your script a few times, then open the text file. What did you notice?


Exercise
Change the "a" into "r". Run your script again, then open the text file. What did you notice? Did the contents of the text file change?

 

file_put_contents( )

You can use the function file_put_contents( ) instead of fwrite( ).

It is used in the same way, but has an optional third parameter:

file_put_contents($file_handle, $file_contents, context);

The context option can be FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX.

So to append to the file, just do this:

file_put_contents($file_handle, $file_contents, FILE_APPEND);

 

In the next part, you'll see how to work with CSV files (comma delimited files).