【问题标题】:PHP Output MS SQL to a downloadable CSV or Excel filePHP 将 MS SQL 输出到可下载的 CSV 或 Excel 文件
【发布时间】:2019-07-13 05:36:06
【问题描述】:

我正在尝试使用 PHP 将 MS SQL 查询返回的数据输出到 Excel 或 CSV 文件。 我在this answer中使用了脚本,可以输出文件OK了。如果没有标题行(在我的代码底部),它会保存在我的服务器的文件夹结构中,而不是作为下载输出到浏览器。

如果我添加标题行,它会输出到 CSV 文件,但会将页面的 HTML 写入文件而不是从数据库中提取!我在某处缺少设置吗?我尝试在没有 HTML 的页面上运行代码(仅限 PHP 和 SQL 代码),但它仍然会发生。

        // Give the file a suitable name:
            $FileName= $PartNumber.".csv";
            $fp = fopen($FileName, 'w');
        // Connect to MS SQL server; the actual database is chosen in the form
        // ConnSQL defined in inc/dbconn/config.php
            ConnSQL($idDatabase);

        // the query is a biggie; here it is:
            require 'inc_sql.php';

        // run it through the SQL server
            $rstBOM = sqlsrv_query($GLOBALS['ConnSQL'], $sqlBOM);

        while ($export= sqlsrv_fetch_array($rstBOM, SQLSRV_FETCH_ASSOC)) {
            if (!isset($headings))
                {
                    $headings = array_keys($export);
                    fputcsv($fp, $headings, ',', '"');
                }
                fputcsv($fp, $export, ',', '"');
            }

        // force download csv - exports HTML to CSV!
            header("Content-type: application/force-download"); 
            header('Content-Disposition: inline; filename="'.$FileName.'"'); 
            header("Content-Transfer-Encoding: Binary"); 
            header("Content-length: ". filesize($FileName)); 
            header('Content-Type: application/excel'); 
            header('Content-Disposition: attachment; filename="'.$FileName.'"');

            fclose($fp);

请问我哪里出错了?

【问题讨论】:

    标签: php sql-server csv download


    【解决方案1】:

    您只需将 csv 文件输出到浏览器即可

    readfile($FileName);
    

    fclose($fp); 函数之后的代码末尾。

    否则,浏览器会收到文件的标头,但没有从您的 PHP 代码发送的内容。

    您也可以即时生成 csv 文件,而只需 echo $csvFileContents;。这将阻止服务器创建数据并将数据写入文件,从而导致安全漏洞。

    祝你好运!

    【讨论】:

    • 感谢您回复我,但这仍然只是将页面 html 输出到 csv 文件。如果我将该行从脚本中取出头文件,则 CSV 信息(来自查询)将写入 html 页面。
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多