d
Amit DhamuSoftware Engineer
 

Write To A Text File

2 minute read 00000 views

Example

$file = fopen('text.txt', 'w');
fwrite($file, 'My new sentence');
fclose($file);

fopen() modes interpolated from PHP.net

# Open for reading only; place the file pointer at the beginning of the file.
'r'

# Open for reading and writing; place the file pointer at the beginning of the file.
'r+'

# Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length.
# If the file does not exist, attempt to create it.
'w'

# Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length.
# If the file does not exist, attempt to create it.
'w+'

# Open for writing only; place the file pointer at the end of the file.
# If the file does not exist, attempt to create it.
'a'

# Open for reading and writing; place the file pointer at the end of the file.
# If the file does not exist, attempt to create it.
'a+'

# Create and open for writing only; place the file pointer at the beginning of the file.
# If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING.
# If the file does not exist, attempt to create it.
'x'

# Create and open for reading and writing; otherwise it has the same behavior as 'x'.
'x+'

# Open the file for writing only. If the file does not exist, it is created.
# If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x').
# The file pointer is positioned on the beginning of the file.
'c'

# Open the file for reading and writing; otherwise it has the same behavior as 'c'.
'c+'