CSV Export

Hey!

I've written a little function that exports the data entered in the form to a CSV-file that can be read by speadsheet-applications.

Instructions

Forms should have a 'csvfile' field with the name of the file to be written, the name may only contain up to 32 numbers, letters, dashes and underscores.

Add this line just before if (send_mail()) in the script:

if ( eregi ( "^[_0-9a-z-]{1,32}$", $form["csvfile"] )) write_csv();

You need to configure the directory to store the CSV files (trailing slash required!). Make sure files in this folder are not readble by your webserver (outside of your webroot, or for apache you could use .htaccess). Add this line at the beginning of your file

$csvdir = "/var/www/csv/";

Now add this code below that:

function write_csv()
{
global $errors, $form, $csvdir,$invis_array;

// CSV file.
$filename = $csvdir. $form["csvfile"].'.csv';

// Contruct the line to write.
reset($form);
while(list($key,$val) = each($form)){
if (!in_array($key,$invis_array)){
$csvline .= "'".$val."',";
}
}
// Remove last comma.
$csvline = substr($csvline, 0, strlen($csvline)-1);

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

// Open the CSVfile.
if (!$handle = fopen($filename, 'a')) {
$errors[] = '1|Could not open specified CSV-file for writing.';
return false;
}
// Write data to file.
if (fwrite($handle, $csvline) === FALSE) {
$errors[] = '1|Could not wrtite to specified CSV-file.';
return false;
}
} else {
// Try to create the CSV file.
if (!$handle = fopen($filename, 'w')) {
$errors[] = '1|Could not create specified CSV-file.';
return false;
}
reset($form);
while(list($key,$val) = each($form)){
if (!in_array($key,$invis_array)){
$csvheader .= "'".$key."',";
}

}
// Remove last comma.
$csvheader = substr($csvheader, 0, strlen($csvheader)-1);

// Write CSV header to our opened file.
if (fwrite($handle, $csvheader."\n".$csvline) === FALSE) {
$errors[] = '1|Could not wrtite to specified CSV-file.';
return false;
}
fclose($handle);
}
}

User login