PHP: Form data into CSV(Excel File ):-

Techno

Current, time you mostly work on MS -Excel (Microsft Excel ) to save and alignment your data in a file .
but you have to work hard for it. If you want to just type text and create it in excel file then it will be so grateful
. How good would you be to have a fill up a form and just click on a button and generate an Excel file?. You can convert the form data into excel file (CSV) and It’s very simple or you can import CSV(excel data ) into database import CSV(excel data ) into database .

Here we will create a form through the HTML and PHP script for convert the Form data into CSV file.

HTML form to collect the data from the user side. Here we will take the various field. 1. Name. 2.Address. 3. Mobile Number. 4. Email Id. When the user clicks the button the form data will convert into CSV File.


HTML Form Code






When the button is pressed the PHP script will be executed .

PHP code Here

<?php
if(isset($_POST['submit'])){

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

    //if no errors carry on
    if(!isset($error)){

        // Title of the CSV
        $Content = "Name,address,mobileno,email\n";

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

        //set the file name and create CSV file
        $FileName = "Myfile-".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 '

$error

'; } } ?>

Now this time to implement. The final code . Click on Run to execute the script .

Final Code

<?php
if(isset($_POST['submit'])){

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

    //if no errors carry on
    if(!isset($error)){

        // Title of the CSV
        $Content = "Name,address,mobileno,email\n";

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

        //set the file name and create CSV file
        $FileName = "Myfile-".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 '

$error

'; } } ?>





Run