Skip to content

Instantly share code, notes, and snippets.

@strackoverflow
Created August 22, 2011 15:52
Show Gist options
  • Save strackoverflow/1162729 to your computer and use it in GitHub Desktop.
Save strackoverflow/1162729 to your computer and use it in GitHub Desktop.
Auto POST to CSV
<?php
function append($data, $i){
//determine whether this line should have a comma or a newline character
if ($i != count($data) - 1 ) {
$append = ',';
}
else {
$append = "\n";
}
return $append;
}
$redirect = 'http://example.com'; //where the form gets sent on success
$csvPath = getcwd() . 'example.csv'; // make sure this file exists and is writable
//check stuffs
if (!file_exists($csvPath)) {
die ('File '.$csvPath.' does not exist!');
}
if (!is_writable($csvPath)) {
die ('File '.$csvPath.' must be writable!');
}
$fp = fopen($csvPath, 'a');
$output = ''; //write to this string
//asort($_POST);
if (filesize($csvPath) == 0){
//this is an empty file, we need to add the column names to the top!
$i = 0;
foreach ($_POST as $key => $value) {
$output .= $key . append($_POST, $i);
$i++;
}
}
//now write the values
foreach ($_POST as $key => $value) {
$i = 0;
$output .= $value . append($_POST, $i);
$i++;
}
if (fwrite($fp, $output)) {
fclose($fp);
header('Location: ' . $redirect);
}
else {
die ('There was an error writing to the file');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment