PHP fwrite() and fputs() functions are used to write data into file. To write data into a file, you need to use w, r+, w+, x, x+, c or c+ mode.
To write to a file in PHP, you can use several methods. One common approach is to use the fwrite()
function, combined with fopen()
and fclose()
to open and close the file handle respectively. Here’s a basic example:
<?php
// Open a file for writing
$myfile = fopen("example.txt", "w") or die("Unable to open file!");
// Text to be written to the file
$txt = "Hello, world!\n";
// Write the text to the file
fwrite($myfile, $txt);
// Close the file handle
fclose($myfile);
?>
In this example:
fopen("example.txt", "w")
opens the file “example.txt” in write mode. If the file doesn’t exist, it will attempt to create it. If it does exist, it will truncate it (i.e., erase its contents) before writing.fwrite($myfile, $txt)
writes the content of the variable$txt
to the file handle$myfile
.fclose($myfile)
closes the file handle, freeing up system resources.
Make sure the file has the necessary write permissions for the PHP script to be able to write to it. Additionally, always handle potential errors, such as if the file can’t be opened or written to, by using functions like die()
or trigger_error()
, or by implementing more robust error handling mechanisms.