[PHP] Overwrite / append to text file

This is a sample to overwrite / append to existing text file.
The following text files are covered here.

[Text file to read]
text.txt
This is an existing string.

Overwrite text file </h 2>

The overwrite fopens with the parameter “w”.

【Results】
Overwrite.

Append to text file

The append is fopen with the parameter “a”.

【Results】
It is an existing string.
P.S.

memo

  • If there is no file to be read in both overwrite and append, create a new one.
  • The overwrite and append are only the second argument of the fopen function.

You can specify the following for fopen’s mode.

【fopen’s mode】
designation Meaning
r Read-only (error if file does not exist)
w Write only (overwrite existing contents)
a Postscript only (appended to existing content)
r + Read / write (error if file does not exist)
w + Read / write (overwrite existing contents)
a + Read / write append (appended to existing contents)

Leave a Reply