Writing to a File: fwrite


Writing to a File: fwrite

Want to write to a file? You can use fwrite, which works like this:

 fwrite (resource handle, string string [, int length]) 

The fwrite function writes the contents of string to the file stream represented by handle. If the length argument is given, writing will stop after length bytes have been written or the end of the string is reached, whichever comes first.

Note also that fwrite returns the number of bytes written or FALSE if there was an error. In addition, if you're working on a system that differentiates between binary and text files (that is, Windows), the file must be opened with 'b' included in the fopen mode parameter.

Here's an example, phpfwrite.php, Example 7-11. In this case, we're just going to write some multi-line text to a file, text.txt. We start by opening this new file for binary writing; if the file doesn't exist, it'll be created automatically:

 $handle = fopen("text.txt", "wb");         .         .         . 

Now we use some multi-line text, with embedded newline (\n) characters, and we write that text to the file. If there was a problem, we report it; otherwise, we report success:

 $handle = fopen("text.txt", "wb"); $text = "Here\nis\nthe\ntext."; if (fwrite($handle, $text) == FALSE) {     echo "Cannot write to text.txt."; } else {     echo "Created the file text.txt."; }         .         .         . 

All that's left is to close the file, as you see in Example 7-11.

Example 7-11. Using fwrite, phpfwrite.php
 <HTML>     <HEAD>         <TITLE>             Writing a file with fwrite         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Writing a file with fwrite             </H1>             <?php                 $handle = fopen("text.txt", "wb");                 $text = "Here\nis\nthe\ntext.";                 if (fwrite($handle, $text) == FALSE) {                     echo "Cannot write to text.txt.";                 }                 else {                     echo "Created the file text.txt.";                 }                 fclose($handle);             ?>         </CENTER>     </BODY> </HTML> 

You can see the report we get from this application in Figure 7-11, where it's telling us that it wrote the file text.txt successfully.

Figure 7-11. Writing to a file using fwrite.


Typing out the file confirms that it was indeed written correctly:

 Here is the text. 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net