我可以同时启动自动下载csv并在页面上显示文本吗?

时间:2015-01-15 19:12:54

标签: php

我正在想象一个用户要去页面并自动启动下载。他们访问的页面将提供有关如何处理文件的说明。现在,页面文本包含在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.";

?>

1 个答案:

答案 0 :(得分:1)

您有两种选择:

  1. 在页面上显示结果,然后重定向到文件下载。
  2. 使用Javascript,通过AJAX请求加载数据,在页面上显示并重定向到data URI