Skip to content

Instantly share code, notes, and snippets.

@mingodev
Created August 23, 2019 14:22
Show Gist options
  • Save mingodev/e85ee29ba38b255be78ddf4ee1ff4ede to your computer and use it in GitHub Desktop.
Save mingodev/e85ee29ba38b255be78ddf4ee1ff4ede to your computer and use it in GitHub Desktop.
Créer un rapport CSV vite fait
<?php
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=rapport.csv');
ob_start();
$dbHostName = '';
$dbDatabase = '';
$dbUsername = '';
$dbPassword = '';
$dbh = new PDO("mysql:host=" . $dbHostname . ";dbname=" . $dbDatabase, $dbUsername, $dbPassword, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
ob_end_clean();
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('ID', 'Prénom', 'Nom', 'Email', 'Date'));
// fetch the data
$reportSQL = 'SELECT id, first_name, last_name, email, created FROM contacts ORDER BY id';
$sth = $dbh->prepare($reportSQL);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) fputcsv($output, $row);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment