8.2.1 file_put_contents()This is NOT the latest copy of this book; click here for the latest version.
int file_put_contents ( string filename, string data [, int flags [, resource context]])
This function writes to a file with the equivalent of fopen(), fwrite() (the opposite of fread() ), and fclose() - all in one function, just like file_get_contents. It takes two parameters, the filename to write to and the content to write respectively, with a third optional parameter specifying extra flags which we will get to in a moment. If file_put_contents() is successful it returns the number of bytes written to the file, otherwise it will return false.
Using the file_put_contents() function is a breeze - here's an example:
<?php
$myarray[] = "This is line one";
$myarray[] = "This is line two";
$myarray[] = "This is line three";
$mystring = implode("\n", $myarray);
$numbytes = file_put_contents($filename, $mystring);
print "$numbytes bytes written\n"; ?>
Remember you will need to set $filename first - other than that the script is straightforward, and should output "52 bytes written", which is the sum total of the three lines of text plus the two new line characters used to implode() the array. Remember that the new line character is in fact just one character inside files, whereas PHP represents it using two, \ and n.
You can pass in a third parameter to file_put_contents(), which, if set to FILE_APPEND, will act to append the text in your second parameter to the existing text in the file. If you do not use FILE_APPEND the existing text will be wiped and replaced, which is not always the desired behaviour.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|