How can one append new content to an existing file without overwriting the existing content in PHP?
To append new content to an existing file without overwriting the existing content in PHP, you can use the `FILE_APPEND` flag with the `file_put_contents()` function. This flag tells PHP to append the new content to the end of the file instead of overwriting it. You can also use the `fopen()`, `fwrite()`, and `fclose()` functions to achieve the same result.
// Using file_put_contents() function
$file = 'example.txt';
$newContent = "This is the new content to append.";
file_put_contents($file, $newContent, FILE_APPEND);
// Using fopen(), fwrite(), and fclose() functions
$file = 'example.txt';
$newContent = "This is the new content to append.";
$handle = fopen($file, 'a');
fwrite($handle, $newContent);
fclose($handle);
Keywords
Related Questions
- What are the best practices for handling calculations and data manipulation in PHP when working with database tables?
- What are some best practices for efficiently reading MySQL rows into arrays in PHP?
- What functions can be used in PHP to check for specific substrings in a string and separate strings at a certain point?