Skip to content

Instantly share code, notes, and snippets.

@michaelaguiar
Created November 22, 2011 18:52
Show Gist options
  • Select an option

  • Save michaelaguiar/1386520 to your computer and use it in GitHub Desktop.

Select an option

Save michaelaguiar/1386520 to your computer and use it in GitHub Desktop.
PHP - Export database into CSV File
<?php
/**
* @title CSV Export - Export database into CSV File
* @author Michael Aguiar <mike@aliasproject.com>
* @copyright 2011 - 2011 Alias Project, Inc.
*/
mysql_connect('HOST', 'USER', 'PASS') or die(mysql_error());
mysql_select_db('DATABASE') or die(mysql_error());
$table = 'TABLE';
exportCSV($table, 'filename.csv');
function exportCSV($table, $filename) {
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$sql_query = "select * from $table";
// Gets the data from the database
$result = mysql_query($sql_query);
$fields_cnt = mysql_num_fields($result);
$schema_insert = '';
for ($i = 0; $i < $fields_cnt; $i++) {
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
}
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
// Format the data
while ($row = mysql_fetch_array($result)) {
$schema_insert = '';
for ($j = 0; $j < $fields_cnt; $j++) {
if($row[$j] == '0' || $row[$j] != '') {
if($csv_enclosed == '') {
$schema_insert .= $row[$j];
} else {
$schema_insert .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
}
} else {
$schema_insert .= '';
}
if ($j < $fields_cnt - 1) {
$schema_insert .= $csv_separator;
}
} // end for
$out .= $schema_insert;
$out .= $csv_terminated;
} // end while
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment