ninigi ninigi - 7 months ago 16
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>
<html>
<body>

<h2>AJAX</h2>
<script>
<?php
if(isset($_POST['submit'])){

//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
if(!isset($error)){

# 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;
exit();
}
}

//if their are errors display them
if(isset($error)){
foreach($error as $error){
echo "<p style='color:#ff0000'>$error</p>";
}
}
?>
</script>
<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>
</form>

</body>
</html>

Answer

You've commented ; character

Change:

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

To:

$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);
Comments