Appending to a File: fwrite


Appending to a File: fwrite

In the previous chunk, we created and wrote to a new file, text.txt. But you may not want to do thatyou may want to append new text to the file instead of overwriting what's already there, as when someone has added a new comment to a guest book.

In this case, you open the file for appending, using the file mode 'a':

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

We'll append this text to text.txt:

 And here is more text. 

You can do that with fwrite much as we wrote the original text, as you see here:

 $handle = fopen("text.txt", "ab"); $text = "\nAnd\nhere\nis\nmore\ntext."; if (fwrite($handle, $text) == FALSE) {     echo "Cannot write to text.txt."; } else {     echo "Appended to the file text.txt."; } 

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

Example 7-12. Using fwrite to append text to a file, phpappend.php
 <HTML>     <HEAD>         <TITLE>             Appending to a file with fwrite         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Appending to a file with fwrite             </H1>             <?php             $handle = fopen("text.txt", "ab");             $text = "\nAnd\nhere\nis\nmore\ntext.";             if (fwrite($handle, $text) == FALSE) {                 echo "Cannot write to text.txt.";             }             else {                 echo "Appended to the file text.txt.";             }             fclose($handle);             ?>         </CENTER>     </BODY> </HTML> 

This example reports success, as you see in Figure 7-12.

Figure 7-12. Appending to a file using fwrite.


You can confirm what's happened by typing out text.txt, which shows this result:

 Here is the text. And here is more 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