2 Ways To Write & Append To Files In PHP (Simple Examples)

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:

  1. 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);
  2. 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!

ⓘ 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.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

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

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

PHP WRITE FILE EXAMPLES

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

 

EXAMPLE 1) WRITE TO FILES USING PUT CONTENTS

1-put-contents.php
<?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

2-write-append.php
<?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 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.

 

EXAMPLE 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.

 

 

EXAMPLE 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"); }
 
// (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

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.

 

 

USEFUL BITS & LINKS

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

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

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

 

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 “2 Ways To Write & Append To Files In PHP (Simple Examples)”

Leave a Comment

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