PHP provides various functions to write data into file:
The PHP fwrite() function is used to write the contents of string to the file.
You need to open the file in r+, w, w+, x, x+, c or c+mode.
Syntax
fwrite(file handle, string)
Example
<?php $filename = "data.txt"; $fp = fopen($filename, 'w'); // opens file in write-only mode fwrite($fp, "data 1\n"); // \n is escape string represents new line fwrite($fp, "data 23"); fclose($fp); ?>
data.txt
data 1 data 23
An alternative way to write data into file is using the file_put_contents()
function.
Syntax
file_put_contents($filename, $data,[$flags])
$flags - FILE_APPEND: append the content to the end of the file
$flags - LOCK_EX: prevent anyone else writing to the file at the same time
<?php $filename = "data.txt"; $data = " data string "; file_put_contents($filename, $data); $data = " append content "; file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); ?>
data.txt
data string append content