forked from smalos/nuBuilder4-Code-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BrowseDownloadToCSV.php
67 lines (53 loc) · 1.93 KB
/
BrowseDownloadToCSV.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Use nuBuilder config file for db settings
include("nuconfig.php");
// Set the CSV delimiter
$delimiter = ';';
// Default file name if no has cookie (browse_export_filename) passed
$default_file_name = 'browse-export.csv';
// Setup the filename that our CSV will have when it is downloaded.
$fileName = "#browse_export_filename#";
if (strpos($fileName, '#') === 0) {
$fileName = $default_file_name;
}
//Connect to the DB using PDO.
try {
$pdo = new PDO("mysql:host=$nuConfigDBHost;dbname=$nuConfigDBName", $nuConfigDBUser, $nuConfigDBPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
//Retrieve the Browse SQL from hash cookie
$sql = json_decode(base64_decode("#browse_sql#"));
// Test with: $sql = "SELECT * FROM `zzzzsys_user` LIMIT 20";
//Prepare the SQL query.
$statement = $pdo->prepare($sql);
//Execute the SQL query.
$statement->execute();
//Fetch all of the rows from our table
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
//Get the column names.
$columnNames = array();
if(!empty($rows)){
//We only need to loop through the first row of our result
//in order to collate the column names.
$firstRow = $rows[0];
foreach($firstRow as $colName => $val){
$columnNames[] = $colName;
}
}
//Set the Content-Type and Content-Disposition headers to force the download.
header('Content-Type: application/excel');
header('Content-Encoding: UTF-8');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
//Open up a file pointer
$fp = fopen('php://output', 'w');
//Start off by writing the column names to the file.
fputcsv($fp, $columnNames, $delimiter);
//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
fputcsv($fp, $row, $delimiter);
}
//Close the file pointer.
fclose($fp);