[ Team LiB ] Previous Section Next Section

Writing or Appending to a File

The processes for writing to a file and appending to a file are similar. The difference lies in the fopen() call. When you write to a file, you should use the mode argument "W" when you call fopen():


$fp = fopen( "test.txt", "w" );

All subsequent writing occurs from the start of the file. If the file doesn't already exist, it is created. Conversely, if the file already exists, any prior content is destroyed and replaced by the data you write.

When you append to a file, you should use mode "a" in your fopen() call:


$fp = fopen( "test.txt", "a" );

Any subsequent writes to your file are added to the existing content.

Writing to a File with fwrite() or fputs()

fwrite() accepts a file resource and a string; it then writes the string to the file. fputs() works in exactly the same way:


fwrite( $fp, "hello world" );
fputs( $fp, "hello world" );

Writing to files is as straightforward as that. Listing 11.13 uses fwrite() to print to a file. We then append a further string to the same file using fputs().

Listing 11.13 Writing and Appending to a File
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 11.13 Writing and Appending to a File</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $filename = "test2.txt";
12: print "Writing to $filename<br/>";
13: $fp = fopen( $filename, "w" ) or die("Couldn't open $filename");
14: fwrite( $fp, "Hello world\n" );
15: fclose( $fp );
16: print "Appending to $filename<br/>";
17: $fp = fopen( $filename, "a" ) or die("Couldn't open $filename");
18: fputs( $fp, "And another thing\n" );
19: fclose( $fp );
20: ?>
21: </div>
22: </body>
23: </html>
    [ Team LiB ] Previous Section Next Section