Search code examples
phparraysfputcsv

Creating HTML Form Fields Into Arrays


16-Jun-16

Hi, I have an HTML form with text, radio buttons, check boxes, and text area fields. I want to write all the fields into a CSV file. It is writing to the CSV file, but unfortunately if there is a comma in any of the fields, it moves the text after the comma to the next field.

I did some research and found I should use 'fputcsv'. All the examples that I found were getting their data from a database, and creating an array. I would like to know how to create an array from the data in my form so I can use it with 'fputcsv'. Below is a sample of my code.

// Create file. If file has been created, open file.
$myfile = fopen("ZZZmycsv.csv", "a") or die("Unable to open file!");

// Write to file.
// Column headers
$msg = "First Name, Last Name, Organization, Email, City, State, Comment 1, Comment 2 \n";

// Form variables
$msg .= "$firstName, $lastName, $organization, $email, $city, $state, $comment1, $comment2 \n";

Please be as detailed as possible with your answers.

Thanks in advance for your time and consideration.


Solution

  • If you use fputcsv, there is already a default escape character ("\") so all you have to do is make an array from the form inputs and write them into the file.

    // Create file. If file has been created, open file.
    $myfile = fopen("ZZZmycsv.csv", "a") or die("Unable to open file!");
    
    // Write to file.
    // Column headers
    $headers = array('First Name', 'Last Name', 'Organization', 'Email', 'City', 'State', 'Comment 1', 'Comment 2');
    fputcsv($myfile, $headers);
    
    // Form variables
    $formArray = array($firstName, $lastName, $organization, $email, $city, $state, $comment1, $comment2);
    fputcsv($myfile, $formArray);
    

    In this example i wrote the headers into the file too, but if you're using fopen(..., "a"); this will possibly make no sense so you may want to use "w" as parameter (not if you want to store more than 1 line in the file. then dont write headers before each line)

    hope this helped, cheers