Skip to content

Instantly share code, notes, and snippets.

@tmilewski
Created August 25, 2010 18:47
Show Gist options
  • Save tmilewski/550060 to your computer and use it in GitHub Desktop.
Save tmilewski/550060 to your computer and use it in GitHub Desktop.
<?php
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$db = new mysqli('[HOST]', '[USERNAME]', '[PASSWORD]', '[DATABASE]');
$result = $db->query("SELECT * FROM [TABLE]");
$field_count = $result->field_count;
$insert = '';
for ($i = 0; $i < $field_count; $i++) :
$insert .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes($result->fetch_field_direct($i)->name)) . $csv_enclosed;
$insert .= $csv_separator;
endfor;
$csv = trim(substr($insert, 0, -1));
$csv .= $csv_terminated;
while ($row = $result->fetch_array()) :
$insert = '';
for ($j = 0; $j < $field_count; $j++) :
if ($row[$j] == '0' || $row[$j] != '') :
if ($csv_enclosed == '') :
$insert .= $row[$j];
else :
$insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
endif;
else:
$insert .= '';
endif;
if ($j < $field_count - 1) $insert .= $csv_separator;
endfor;
$csv .= $insert;
$csv .= $csv_terminated;
endwhile;
$result->close();
$db->close();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($csv));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=export.csv");
echo $csv;
exit;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment