Skip to content

Instantly share code, notes, and snippets.

@vishwapriyanatha
Last active April 27, 2017 06:22
Show Gist options
  • Save vishwapriyanatha/65fd17293a2e65438273f9ce19e5c8c3 to your computer and use it in GitHub Desktop.
Save vishwapriyanatha/65fd17293a2e65438273f9ce19e5c8c3 to your computer and use it in GitHub Desktop.
create and download a csv file from php script
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$query = "select * from user table";
$result = mysqli_query($con,$query);
$array_key = ((array) $result[0]);
$headers = (object) array_keys($array_key);
$delimiter = ",";
$filename = 'process.csv';
$f = fopen('php://memory', 'w');
fputcsv($f, (array)$headers, $delimiter);
foreach ($result as $line) {
$phpar = (array) $line;
fputcsv($f, $phpar, $delimiter);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment