Add a new line to a CSV file

If I have a CSV saved on a server, how can I use PHP to write a given line, say 142,fred,elephants to the bottom of it?


Open the CSV file for appending (fopen­Docs):

$handle = fopen("test.csv", "a");

Then add your line (fputcsv­Docs):

fputcsv($handle, $line); # $line is an array of strings (array|string[])

Then close the handle (fclose­Docs):

fclose($handle);

You can use an object oriented interface class for a file - SplFileObject http://php.net/manual/en/splfileobject.fputcsv.php (PHP 5 >= 5.4.0)

$file = new SplFileObject('file.csv', 'a');
$file->fputcsv(array('aaa', 'bbb', 'ccc', 'dddd'));
$file = null;