我正在想象一个用户要去页面并自动启动下载。他们访问的页面将提供有关如何处理文件的说明。现在,页面文本包含在csv文件中,而不是回显到页面。这甚至可以在一个脚本中?这是我的代码......
<?php
function databaseConnection() {
$conn = new PDO("sqlsrv:server=IP ; Database=database",'user','password');
return $conn;
}
function getStudents() {
global $conn;
$studentsql =
"SQL query";
$studentquery = $conn->prepare($studentsql);
$studentquery->execute();
$studentarray = array();
while ($studentrow = $studentquery->fetch(PDO::FETCH_ASSOC)) {
$studentarray[] = $studentrow;
}
return $studentarray;
}
function createFile($fileheader,$filebody) {
$file = fopen('php://memory', 'w');
fputcsv($file, $fileheader);
foreach ($filebody as $key => $students) {
fputcsv($file, $students);
}
rewind($file);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
fpassthru($file);
fclose($file);
}
$conn = databaseConnection();
$fileheader = array("header1","header2");
createFile($fileheader, getStudents());
$conn = null;
echo "<p>The file has automatically downloaded and was placed in your downloads folder.</p>
<p>Double clicking the file will automatically open it in Excel. You should then go to File | Save As <br>
and choose a different name and save it as an excel file by choosing .xlsx as the file type.";
?>