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?
Since the line break \n is almost always used as a row terminator, it has a special meaning in CSV files and can therefore confuse a parser when it occurs within a text column.
Including the newline parameter allows the csv module to handle the line endings itself - replicating the format as defined in your csv.
To append/add something to an existing file, simply specify the second parameter to be true as following: FileWriter fstream = new FileWriter(loc, true); FileWriter fstream = new FileWriter(loc, true); This will keep adding content to the existing file instead of creating a new version.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With