How To Write & Append To Files In PHP – Simple Examples

Welcome to a beginner’s 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 to files in PHP:

  • The easier wayfile_put_contents("FILE", "STRING TO WRITE");
  • Or create/open a file, then write to it.
    • $fh = fopen("FILE", "w");
    • fwrite($fh, "STRING TO WRITE");
    • fclose($fh);

That should cover the quick basics, but if you need more examples – Read on!

ⓘ I have included a zip file with all the example source code at the start of the tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK TUTORIAL

 

TABLE OF CONTENTS

Download & Notes Write File Examples Useful Bits & Links
The End

 

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

PHP WRITE FILE EXAMPLES

All right, let us now go into the various examples on how to write to files in PHP.

 

1. WRITE TO FILES USING PUT CONTENTS

1-put-contents.php
<?php
// NOTE: FILE WILL BE OVERRIDEN!
file_put_contents("demo.txt", "This will always override the file.");
echo "DONE!";

// TO APPEND, PASS IN AN "APPEND" FLAG
// file_put_contents("demo.txt", "Data", FILE_APPEND);

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.

 

 

2. WRITE & APPEND USING FOPEN

2-write-append.php
<?php
// (A) WRITE TO FILE
// NOTE: 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);
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 and a 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. Yes, it is highly recommended to do so, if you don’t want 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.

 

3. ADDING NEW LINES

3-new-lines.php
// (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) CLOSE
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.

 

 

4. WRITE ARRAY TO FILE, LINE-BY-LINE

4-write-array.php
<?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");
}
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().

 

5. WRITING AN ARRAY TO CSV FILE

5-write-csv.php
<?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.

 

 

THE SUMMARY

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

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

 

CHEAT SHEET

How To Write Data To Files In PHP (Click to Enlarge)

 

MORE LINKS

 

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!

1 thought on “How To Write & Append To Files In PHP – Simple Examples”

Leave a Comment

Your email address will not be published. Required fields are marked *