ninigi ninigi - 8 months ago 24
PHP Question

Save data from HTML form into .CSV filve using PHP

I'm struggling a bit with obtaining data from my form and saving it to CSV file via PHP. This code is not working and I run out of ideas how to fix it. Is there anything wrong with the way I save it to CSV file? I'd be grateful for your help.

The code is supposed to work this way: I want the user to input some data to HTML form. Then with the usage of AJAX and PHP I want to save it to a csv file. The saving doesn't work - the file stays empty.

<!DOCTYPE html>


//collect form data
$name = $_POST['name'];
$email = $_POST['email'];

//check name is set
if($name ==''){
$error[] = 'Name is required';

//check for a valid email address
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';

//if no errors carry on

# Title of the CSV
$Content = "Name, Email\n";

//set the data of the CSV
$Content .= "$name, $email\n";

# set the file name and create CSV file
$FileName = "sth.txt"//"formdata-".date("d-m-y-h:i:s").".csv";
// header('Content-Type: application/csv');
// header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;

//if their are errors display them
foreach($error as $error){
echo "<p style='color:#ff0000'>$error</p>";
<form action='' method='post'>
<p><label>Name</label><br><input type='text' name='name' value=''></p>
<p><label>Email</label><br><input type='text' name='email' value=''></p>
<p><input type='submit' name='submit' value='Submit'></p>



You've commented ; character


$FileName = "sth.txt"//"formdata-".date("d-m-y-h:i:s").".csv";


$FileName = "sth.txt";//"formdata-".date("d-m-y-h:i:s").".csv";

Also I don't see where You save data to file.

So use this example:

$FileName = "sth.txt";
file_put_contents($FileName, $Content);