[Solved] Create a CSV file in php [closed]


Consider this as an example, first off, of course you need a form:

Sample Form:

<!-- HTML -->
<form method="POST" action="processes_the_form.php">
    Sr No.: <input type="text" name="srno" /><br/>
    Name: <input type="text" name="name" /><br/>
    Invt.: <input type="text" name="invt" /><br/>
    <input type="submit" name="submit" value="Add to CSV" />
</form>

Then process it in PHP:

<?php
// set delimitter (tab or comma)
$delimitter = chr(9); // this is a tab
$newline = "\r\n"; // CRLF or whatever you want

// handle form submit
if(isset($_POST['submit'])) {
    // gather values
    $srno = $_POST['srno'];
    $name = $_POST['name'];
    $invt = $_POST['invt'];

    // check for the csv file
    $directory = ''; // sample: path/to/csv/
    $prefix = 'Test_';
    $date = date('d-m-Y');
    $file_path = $directory . $prefix . $date . '.csv';

    // initial creation
    if(!file_exists($file_path)) {
        $file = fopen($file_path, 'w');
        // add the headers
        $headers = array('SrNo', 'Name', 'Invt');
        fputcsv($file, $headers, $delimitter);
        fclose($file);
    }

    $formatted_data = array($srno, $name, $invt);
    // put them inside the file and append on end
    $file = fopen($file_path, 'a');
    fputcsv($file, $formatted_data, $delimitter);
    fclose($file);
}

?>

Note: You may need to set your permissions to that PHP to create/write on that particular path

solved Create a CSV file in php [closed]