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 ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.