8.2.2 fwrite()This is NOT the latest copy of this book; click here for the latest version.
int fwrite ( resource handle, string string [, int length])
The opposite to fread() is fwrite() and also works with the file handle returned by fopen(). Fwrite() takes a string to write as a second parameter, and an optional third parameter where you can specify how many bytes to write. If you do not specify the third parameter, all of the second parameter is written out to the file, which is often what you want.
Author's Note: as with fread(), PHP will stop writing when it reaches the end of the string or when it has reached the number of bytes specified in this length parameter, whichever comes first - you do not need to worry about specifying more bytes than you have in the string.
Here is an example using the variable $mystring from the previous example to save space:
<?php
$handle = fopen($filename, "wb");
$numbytes = fwrite($handle, $mystring);
fclose($handle);
print "$numbytes bytes written\n"; ?>
If I had added 10 as the third parameter to the fwrite() call, only the first ten bytes of $mystring would have been written out. Note again that fclose() is called immediately after it was finished with, which is always best practice.
Fwrite() uses a file pointer in the same way as fread() - as you write bytes out, PHP advances the file pointer appropriately, meaning that, unless you specifically move the file pointer yourself, you always write to the end of a file.
|
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!
|