I have a form on a website that once completed holds the values in an array. I wish to put the contents of the array into a txt file, each submission on a new line, values seperated by ‘-‘:
info-info-info-info
info-info-info-info
I’ve tried using:
foreach ($clean as $info) {
$file = fopen("userinfo.txt", "w");
fwrite($file, $info);
fclose($file);
}
This only put the last part of the array in the text file and overwrites the file on each submission.
Using:
$results = var_export($clean, true);
file_put_contents('userinfo.txt', $results);
writes all the info to the file correctly but stores as a var dump, and overwrites on each submission. I don’t know how to format it to achieve what I need. Any help greatly appreciated.
You are basically writing a CSV (comma-separated values) file. PHP has the right function to do the job builtin:
fputcsv(As an added bonus it will also properly handle escaping of values containing the separator themselves);Use
fgetcsvto retrieve the data at a later point.