A better file append with PHP

Mon, 23 March 2020

php
file_append_contents.php
<?php
/**
 * @param string $filename Path to the file where to write the data.
 * @param mixed $data The data to write. Can be either a string, an array or a stream resource.
 * @param resource $context [optional] A valid context resource created with stream_context_create.
 * @return false|int
 */
function file_append_contents($filename, $data, $context = null)
{
    if (substr($data, strlen(PHP_EOL)) !== PHP_EOL && substr($data, 0-strlen(PHP_EOL)) !== PHP_EOL) {
        $data = $data . PHP_EOL;
    }
    return file_put_contents($filename, $data, FILE_APPEND, $context);
}
usage.php
<?php
file_append_contents('output.txt', 'This is some content', null);
file_append_contents('output.txt', 'This is some more content', null);
output.txt
This is some content
This is some more content
php