I want to append form data in a CSV file that is stored on the server, the data should be added as a new row. I tried
$list = array(
'Peter,Griffin,Oslo,Norway,Norway,Norway,Norway,Norway',
'Glenn,Quagmire,Oslo,Norway,Norway,Norway,Norway,Norway',
);
print_r($list);
$file = fopen('db.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line){
fputcsv($file,explode(',',$line));
}
fclose($file);
but can't add data at the end of the file. How can i achieve this?
You should open your CSV file in append mode
fopen(FILENAME, 'a');before callingfputcsv():It's important that you have write permission on the CSV file if not you won't be able to append data to it. The user and group of the file may not be the same as the PHP process. This depends a lot on your hosting service. The best would be to check that your SSH or FTP user is in the same group than the PHP running your web site. If both are in the same group then you can just give write permission to the user and group and only read for other users:
Or even no read permission to other users, which would be even better:
Up to you to see what's the best to do. You can also change the user and group of the file with
chown username db.csvorchgrp groupname db.csvor evenchown username:groupname db.csv.Your code where I replaced the
explode(',', $line)bypreg_split('/\s*,\s*/', $line)in order to handle eventual spaces around the comma character: