The simple way to write to or create a file. Just give this function the file path and the data to put in it, and away it goes. If the file doesn’t exist, it will be created. If the file does exist, the contents will be overwritten (see flags below).

The data can be a string, array, or a data stream. If it’s an array, it will be written as if you’d converted it to a string with

$data = implode( '', $data );

The optional third parameter allows you to set flags for specific behaviour. More than one can be used by separating them with the pipe (|).

FILE_USE_INCLUDE_PATH: Search for the file in the include directory.
FILE_APPEND: Append the data to the file instead of overwriting it (creates file and writes as normal if file doesn’t exist).
LOCK_EX (since PHP 5.1.0): Lock the file for writing. Not needed with FILE_APPEND.
FILE_TEXT (since PHP 6.0): Data is written in text mode.
FILE_BINARY (since PHP 6.0): Data is written in binary mode.

$file = 'output.txt';
 
$data = "All the laddies cat call and wolf whistle
So-called gentlemen and ladies
Dog fight like rose and thistle";
file_put_contents( $file, $data );
/*
All the laddies cat call and wolf whistle
So-called gentlemen and ladies
Dog fight like rose and thistle
*/
 
$data = array( 'All the laddies cat call and wolf whistle',
               'So-called gentlemen and ladies',
               'Dog fight like rose and thistle' );
file_put_contents( $file, $data );
/*
All the laddies cat call and wolf whistleSo-called gentlemen and ladiesDog fight like rose and thistle
*/
 
// using FILE_APPEND
 
$data = "This first write creates a new file
and I'll put a new line at the end of it
";
file_put_contents( $file, $data );
 
$data = "This second write will append the first.
Oh, what fun!";
file_put_contents( $file, $data, FILE_APPEND );
/*
This first write creates a new file
and I'll put a new line at the end of it
This second write will append the first.
Oh, what fun!
*/