php - 从服务器下载 CSV 文件

标签 php csv

我正在查询我的数据库并使用结果创建 csv 文件。然后我在前端页面上放置了一个指向在服务器上创建的文件的链接,如下所示:

function writetofile($stringData, $myFile) {
     $fh = fopen('download/'.$myFile, 'w') or die("can't open file");
     fwrite($fh, $stringData);
     fclose($fh);
}

$filename = $file."_".date("d-m-Y_H-i",time()).'.csv';

writetofile($seperator, $filename);
print 'Right-click on the link below and select "Save as":' . '<br/><br/>';
print 'Download File: <a href="/download/'.$filename.'" target="_blank">Download Link</a>'; 

出于某种原因,当我直接从服务器下载文件时,数据库中的所有行看起来都是正确的。但是,当我执行用户将执行的步骤(即右键单击并保存)时,该文件仅包含此页面的 html 代码。

最佳答案

更新看看 http://php.net/manual/en/function.readfile.php

放入合适的php header ,输出文件内容并退出:

<?php // none space here
function writetofile($stringData, $myFile)
{
    if ( ! file_exists('download/' . $myFile))
    {
        echo 'file missing';
    }
    else
    {
        header('HTTP/1.1 200 OK');
        header('Cache-Control: no-cache, must-revalidate');
        header("Pragma: no-cache");
        header("Expires: 0");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=$myFile");
        readfile('download/' . $myFile);
        exit;
    }
}

无论如何都要调查http://php.net/manual/en/function.fputcsv.php确保正确的 csv 格式...

关于php - 从服务器下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14106343/

相关文章:

php - Eloquent groupBy 在 Laravel 5.3 中使用有效的 SQL 查询生成 "SQLSTATE[42000]"

php - liip_imagine with vich_uploader 不创建缓存

PHP加密&VB.net解密

r - ggplot2:按字母顺序排列图例,而不是按照数据集中出现的顺序

python - 从 pandas 数据帧写入 .csv 文件,并使用连续空格作为分隔符

python - 将 Dataframe 保存到 csv 直接保存到 s3 Python

php - MSSQL 到 MYSQL 链接服务器插入查询问题

PHP:裁剪文件/目录路径

java - 如何使用 Open CSV 不将双引号加倍?

csv - API 网关 + Lambda 下载 CSV 文件