Skip to content

Instantly share code, notes, and snippets.

@fhdalikhan
Created June 25, 2019 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fhdalikhan/05fb7d6c44522116b789c0a8f01956a4 to your computer and use it in GitHub Desktop.
Save fhdalikhan/05fb7d6c44522116b789c0a8f01956a4 to your computer and use it in GitHub Desktop.
export csv using fputcsv in PHP
<?php
function export(){
$filename = 'users_'.date('Ymd').'.csv';
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=test_db;host=127.0.0.1';
$user = 'test';
$password = 'test';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT * FROM TABLE_NAME";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
// file creation
$file = fopen('php://output', 'w');
$header = array("Category Name","Product Name","Price","Detail","Description");
fputcsv($file, $header);
foreach ($result as $key=>$line){
fputcsv($file,$line);
}
fclose($file);
exit;
}
export();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment