Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add lines to a CSV file without overwriting it

Tags:

php

csv

fputcsv

$file = fopen("contacts.csv","w");
foreach(array_unique($matches[0]) as $email) {
    fputcsv($file,explode(',',$email));
}
fclose($file);

The above code generates a CSV file. How can I update the CSV from the last recorded line without overwriting from the beginning?

like image 207
troshan Avatar asked Jul 21 '15 15:07

troshan


1 Answers

Change "w" to "a" in the fopen. It changes "write" into "append".

"append" opens the file and writes at the end of the file, not from the beginning like "write".

i.e. change this line

$file = fopen("contacts.csv","w");

to

$file = fopen("contacts.csv","a");

like image 109
Ehab Eldeeb Avatar answered Sep 24 '22 14:09

Ehab Eldeeb