Create & Update CSV on form submission [RESOLVED]

For future reference, below is the code I ended up with. It looks to see if the CSV file exists - If not, the headers are created and related data appended. If the file exists, the form data is simply appended to a new row in the CSV file.

The reason behind creating this script is to feed real-time form data to our Qlik server. With this data, we can display a “prettified” version to almost any digital medium.

function populate_csv( $entry, $form ) {

//Headers info
$headers = array('Nominee', 'Reason1', 'Reason2', 'Reason3', 'Justification');

//Build form data
$data = array(
    'Nominee' => rgar( $entry, '1' ),
    'Reason1' => rgar( $entry, '4.1' ),
    'Reason2' => rgar( $entry, '4.2' ),
    'Reason3' => rgar( $entry, '4.3' ),
    'Justification' => rgar( $entry, '3' ), 
             );

// check if the file exists or not to determine if headers are needed
$headersNeeded = !file_exists('Nominations.csv');

//Open or Create CSV File
$fh = fopen('Nominations.csv', 'a');

// if headers are needed, add them  
if ($headersNeeded){
    //Create headers
    fputcsv($fh, $headers);
}
//Populate the data 
fputcsv($fh,$data);

//Close the file
fclose($fh);
}
add_action( 'gform_after_submission_11', 'populate_csv', 10, 2 );
1 Like