Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 28, 2023 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/4616abff35b2005a2a5da71f7b2566e0 to your computer and use it in GitHub Desktop.
Save code-boxx/4616abff35b2005a2a5da71f7b2566e0 to your computer and use it in GitHub Desktop.
PHP Write & Append To Files

PHP WRITE & APPEND TO FILES

https://code-boxx.com/write-append-files-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?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!";
<?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!";
<?php
// (A) OPEN/CREATE FILE
$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!";
<?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!";
<?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!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment