Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new line to a CSV file

Tags:

php

csv

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?

like image 753
Damon Avatar asked Jul 09 '12 16:07

Damon


People also ask

Can csv have line break?

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.

What is the use of newline in CSV file?

Including the newline parameter allows the csv module to handle the line endings itself - replicating the format as defined in your csv.

How do I add a new row to an existing CSV file in Java?

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.


2 Answers

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); 
like image 71
hakre Avatar answered Sep 18 '22 16:09

hakre


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; 
like image 42
elshnkhll Avatar answered Sep 21 '22 16:09

elshnkhll