-2

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?

Mukash Wasti
  • 135
  • 1
  • 16
  • 2
    What do you mean by _"but can add data at the end of the file"_? Isn't that what you want and what that function does? Please clarify (give us a proper example) and also include your actual code (we don't know what your implementation looks like). It's a bit too unclear atm. – M. Eriksson Jan 21 '22 at 10:03
  • Use `a` or `a+` option when opening the file to append to the end of it when writing. Then just fputcsv. Or manually move the pointer to its end with `fseek`. https://www.php.net/manual/de/function.fopen – Code Spirit Jan 21 '22 at 10:05
  • @M.Eriksson, edited it – Mukash Wasti Jan 21 '22 at 10:08
  • @CodeSpirit i am already using "a" $list = array ( 'Peter,Griffin,Oslo,Norway', 'Glenn,Quagmire,Oslo,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); die(); – Mukash Wasti Jan 21 '22 at 10:09
  • 1
    Please [edit](https://stackoverflow.com/posts/70799472/edit) your question to include your code instead of posting it in comments (it's pretty unreadable) – M. Eriksson Jan 21 '22 at 10:10
  • code included please check – Mukash Wasti Jan 21 '22 at 10:15
  • So what is your actual issue with the above code? When I tried it, it keeps adding the rows at the end of the file. Can you please show us an example of how you expect that data to be inserted? Show us what you expect your `db.csv` after you've run that code. Are you trying to insert that data in _one_ row (which it currently does), or are you expecting it to insert each comma separated values as new rows? Or don't you get _anything_ in your file? Does PHP have write permission to that folder/file? – M. Eriksson Jan 21 '22 at 10:26
  • By _can't add data at the end of the file_ Do you mean you want to append data to the end of an existing file, i.e. add line to a file you already have? – RiggsFolly Jan 21 '22 at 10:26
  • the code is working fine, the issue is with permissions.. Thankyou – Mukash Wasti Jan 21 '22 at 10:39
  • 1
    @MukashWasti - For the next time: this is why it's _super important_ that you give a _clear and precise_ description of your issue. Then we can probably figure it out _much_ faster. – M. Eriksson Jan 21 '22 at 10:54

1 Answers1

2

You should open your CSV file in append mode fopen(FILENAME, 'a'); before calling fputcsv():

<?php

define('FILENAME', 'file.csv');

$lines = [
   ['aaa', 'bbb', 'ccc'],
   ['123', '456', '789'],
   ['Quotes " get repeated twice', 'If commas , then it will be surounded by quotes', 'ccc'],
];

// Fill the CSV file.
$file = fopen(FILENAME, 'w');
foreach ($lines as $fields) {
    fputcsv($file, $fields);
}
fclose($file);

// Add a new line at the end of the file
$file = fopen(FILENAME, 'a');
fputcsv($file, ['another', 'line', 'at the end']);
fclose($file);

?>

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:

chmod ug=rw,o=r db.csv

Or even no read permission to other users, which would be even better:

chmod ug=rw,o= db.csv

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.csv or chgrp groupname db.csv or even chown username:groupname db.csv.

Your code where I replaced the explode(',', $line) by preg_split('/\s*,\s*/', $line) in order to handle eventual spaces around the comma character:

<?php

// Just to see the var_export() in plain text instead of HTML.
header('Content-Type: text/plain;charset=utf-8');

// With spaces or tabs around the commas for the preg_split() demo.
$lines = array(
    "Peter,\tGriffin,Oslo,   Norway,Norway  ,Norway, Norway,Norway",
    'Glenn, Quagmire, Oslo, Norway, Norway, Norway, Norway, Norway',
);

var_export($lines);

$file = fopen('db.csv', 'a');

foreach ($lines as $line) {
    fputcsv($file, preg_split('/\s*,\s*/', $line));
}
    
fclose($file);

?>
Patrick Janser
  • 3,318
  • 1
  • 16
  • 18
  • i added my code – Mukash Wasti Jan 21 '22 at 10:14
  • its working fine in the case if i don't put the name of my csv file in define method, but when i add db.csv which is on the server, the code does not effect db.csv – Mukash Wasti Jan 21 '22 at 10:29
  • Is your code working or not? I added your code to my answer and replaced the `explode()` by a `preg_split()` using a regular expression so that it handles eventual spaces around the comma character. It works fine on my computer. – Patrick Janser Jan 21 '22 at 10:29
  • 3
    Have you got write permission on the file on the server? If not, change the user or group so that your PHP user can write the file. Ideally do `chmod ug=rw,o=r db.csv` to grant read and write permission for the file user and group but only read for other users. Or if you have to do it for all users then `chmod ugo=rw db.csv` but it's not very safe as anybody on the server could modify it. – Patrick Janser Jan 21 '22 at 10:30
  • 1
    yup, its the permission issue.. Thankyou – Mukash Wasti Jan 21 '22 at 10:39
  • @MukashWasti I added all the explanation in my answer so that other users have all of it together. – Patrick Janser Jan 21 '22 at 10:45
  • just a quick question.. the code runs fine in any other file, but it does not run from codeigniter controller, as far as i have seen it is opening the file but not putting the data.. please suggest in that too Thanks again. – Mukash Wasti Jan 25 '22 at 08:46
  • Sorry, but I've got no idea why your code would not work if it's moved inside a *CodeIgniter* controller. I never used this framework before. Try to debug your app with *XDebug* and an IDE such as `Visual Studio Code`, `NetBeans`, `PHPStorm`, etc. – Patrick Janser Jan 25 '22 at 08:55