How to write to a file in PHP?


by lizzie , in category: PHP General , a year ago

How to write to a file in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , a year ago


In PHP, you can write to a file using the fwrite() function or the file_put_contents() function. Here are the steps to write to a file using these functions:

Using fwrite():

  1. Open the file using the fopen() function with the w or a mode.
  2. Write the data to the file using the fwrite() function.
  3. Close the file using the fclose() function.

Here's an example code snippet:

$file = fopen("myfile.txt", "w");
fwrite($file, "Hello World!");

Using file_put_contents():

  1. Specify the file name and the data to be written to the file as arguments to the file_put_contents() function.
  2. If you want to append to an existing file, set the FILE_APPEND flag as the third argument.

Here's an example code snippet:

file_put_contents("myfile.txt", "Hello World!");

To append to an existing file:

file_put_contents("myfile.txt", "Hello World!", FILE_APPEND);

Note: You need to have the necessary file permissions to write to a file.