Skip to content

Instantly share code, notes, and snippets.

@rodrigophpweb
Created February 7, 2019 17:34
Show Gist options
  • Save rodrigophpweb/e8c85ddad84ae96fc3cdf26fe7822a6d to your computer and use it in GitHub Desktop.
Save rodrigophpweb/e8c85ddad84ae96fc3cdf26fe7822a6d to your computer and use it in GitHub Desktop.
Função de utilitário para saída de uma consulta mysql para csv com a opção de gravar no arquivo ou enviar de volta para o navegador como um anexo csv.
<?php
function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
}
// Using the function
$sql = "SELECT * FROM table";
// $db_conn should be a valid db handle
// output as an attachment
query_to_csv($db_conn, $sql, "test.csv", true);
// output to file system
query_to_csv($db_conn, $sql, "test.csv", false);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment