Created
June 25, 2019 07:42
-
-
Save fhdalikhan/05fb7d6c44522116b789c0a8f01956a4 to your computer and use it in GitHub Desktop.
export csv using fputcsv in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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