Welcome to a quick tutorial on how to write and append to files in PHP. Need to write some data to a file in your project?
There are 2 common ways to write and append data to files in PHP:
- Write a string to a file.
file_put_contents("FILE.NAME", "DATA");
- To append to an existing file, pass in an append flag –
file_put_contents("FILE.NAME", "DATA", FILE_APPEND);
- Open a file stream and write data to it.
$fh = fopen("FILE", "w")
to create a new stream, or$fh = fopen("FILE", "a")
to append to an existing file.fwrite($fh, "STRING TO WRITE");
fclose($fh);
That should cover the quick basics, but read on if you need more examples!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PHP WRITE FILE EXAMPLES
All right, let us now go into the various examples of how to write files in PHP.
TUTORIAL VIDEO
EXAMPLE 1) WRITE TO FILES USING PUT CONTENTS
<?php
// (A) PUT CONTENTS (WILL OVERRIDE EXISTING)
file_put_contents("demo.txt", "This will always override the file.");
// (B) TO APPEND, PASS IN AN "APPEND" FLAG
file_put_contents("demo.txt", " Appended.", FILE_APPEND);
// (C) DONE
echo "DONE!";
Yep, this is the most convenient fuss-free way to write to file in PHP – Just use the file_put_contents()
function. But take note that it will override the file by default, remember to pass in FILE_APPEND
if you want to append to the file instead.
EXAMPLE 2) WRITE & APPEND USING FOPEN
<?php
// (A) WRITE TO FILE - FILE WILL BE OVERRIDEN!
$fh = fopen("demo.txt", "w");
fwrite($fh, "This will override the entire file!");
fclose($fh);
// (B) TO APPEND - USE "A" INSTEAD OF "W"
$fh = fopen("demo.txt", "a");
fwrite($fh, " This will be appended.");
fclose($fh);
// (C) DONE
echo "DONE!";
This is the “not-so-convenient” way of writing or appending to files in PHP.
$fh = fopen("demo.txt", "w")
opens a file stream to work with. Take note of the second “mode” parameter –w
stands for “write”m anda
stands for “append”. But of course, there are a lot more, I will leave a link to the official PHP manual below if you are interested.fwrite($fh, "STRING")
writes to the file.fclose($fh)
closes the file stream. It is highly recommended to do so because nobody likes a corrupted file.
So why do some “dumb people” go through all the trouble to use this “inconvenient” method? Simply because it offers a lot more controls, and performs way better when dealing with massive amounts of data.
EXAMPLE 3) ADDING NEW LINES
// (A) OPEN/CREATE FILE - LOOP & WRITE
$fh = fopen("demo.txt", "w");
// (B) WRITE LINES
fwrite($fh, "First line.\r\n");
fwrite($fh, "Second line.\r\n");
fwrite($fh, "Third line.\r\n");
// (C) DONE
fclose($fh);
echo "DONE!";
- When it comes to adding new lines, there are 2 “special characters” that you have to know:
\r
for “carriage return” and\n
for “line feed”. - Then comes the painful part – Linux uses
\n
, Mac uses\r
, Windows uses\r\n
. Read on Wikipedia if you are interested. - Most code ninjas just shrug and use
\r\n
regardless, and it is kind of “universally understood” as a single line break.
EXAMPLE 4) WRITE ARRAY TO FILE, LINE-BY-LINE
<?php
// (A) ARRAY OF DATA
$data = ["Apple", "Beet", "Cabbage", "Durian", "Elderberry"];
// (B) OPEN/CREATE FILE - LOOP & WRITE
$fh = fopen("demo.txt", "w");
foreach ($data as $d) { fwrite($fh, $d."\r\n"); }
// (C) DONE
fclose($fh);
echo "DONE!";
This should not be a mystery anymore.
- We open a file using
fopen()
as usual. - Then simply use
foreach()
to loop through the array. - Use
fwrite()
to write each element to the file, line-by-line. - Lastly, close the file properly with
fclose()
.
EXAMPLE 5) WRITING AN ARRAY TO CSV FILE
<?php
// (A) ARRAY OF DATA
$data = [
["Apple", "Beet", "Cabbage"],
["Durian", "Elderberry", "Fennel"],
["Grape", "Honeydew", "Imbe"],
["Jackfruit", "Kiwi", "Lemon"]
];
// (B) OPEN FILE & WRITE
$fh = fopen("demo.csv", "w");
foreach ($data as $row) { fputcsv($fh, $row); }
// (C) DONE!
fclose($fh);
echo "DONE!";
Here is the last example, and a small extra for you guys who are looking to generate reports or spreadsheets. Yes, there is a fputcsv()
function that we can conveniently use to create CSV files.
EXTRAS
That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.
SUMMARY
Function | Description | Reference Link |
file_put_contents(FILE, DATA) |
Write a string to a file. | Click Here |
fopen(FILE) |
Opens a selected file. | Click Here |
fwrite(STREAM, DATA) |
Writes data to the file. | Click Here |
fputcsv(STREAM, DATA) |
Writes a CSV row to the file. | Click Here |
fclose(STREAM) |
Closes the file stream. | Click Here |
LINKS & REFERENCES
- How To Read Files In PHP – Code Boxx
- Absolute & Relative Paths In PHP – Code Boxx
THE END
Thank you for reading, and we have come to the end of this guide. I hope that this has helped you to better understand. If you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!
Great Job