There are several ways to write to a file in PHP, but two common methods are fwrite
and file_put_contents
.
Using fwrite
This method requires opening the file in "write" mode using the fopen
function, and then using the fwrite
function to write the data to the file.
Here is an example:
main.php88 chars4 lines
This code will create a new file called example.txt
(if it doesn't exist) and write the string "Hello World. Testing!" to it.
Using file_put_contents
This method is simpler and more concise. It allows you to write data to a file with just one line of code:
main.php59 chars2 lines
This code will create a new file called example.txt
(if it doesn't exist) and write the string "Hello World. Testing!" to it. Unlike fwrite
, this method automatically closes the file when done.
gistlibby LogSnag