【问题标题】:Using CodeIgniter to download CSV of results使用 CodeIgniter 下载结果的 CSV
【发布时间】:2014-10-15 13:01:13
【问题描述】:

我们使用 CodeIgniter 对我们的 MySQL 数据库运行查询,并在页面上显示这些结果。有时,我们希望将它们下载为 CSV。我之前的那个人设置了这个下载按钮,但它根本不起作用。从来没有。

这是现有的下载代码:

public function download_csv_search(){

    $dbresults = $this->do_search();

    $results = $dbresults['results'];
    $csv = "First Name, Last Name, MI, Age, Details(RA), Status, Home Phone, Gender, Notes\n";

    $filename = "data_export";
    //header('Content-Type: text/csv; charset=utf-8');
    //header('Content-Disposition: attachment; filename=data.csv');
    //$output = fopen('php://output', 'w');
    //fputcsv($output, array('First Name', 'Last Name', 'Middle Name', 'DOB', 'Details(RA)', 'Status', 'Home Phone', 'Gender', 'Notes'));

    foreach($results as $result) {
        $birthday_timestamp = strtotime($result->VoterDOB);  
        $age = date('md', $birthday_timestamp) > date('md') ? date('Y') - date('Y', $birthday_timestamp) - 1 : date('Y') - date('Y', $birthday_timestamp);
        $csv .= $result->VoterFN.",".$result->VoterLN.",".$result->VoterMN.",".$dob.",".$result->Street.",".$result->VoterStatusID.",".$result->phone.",N/A,\n";
    //  $dataArray = array('VoterFN'=>$result->VoterFN, 'VoterLN'=>$result->$VoterLN, 'VoterMN'=>$result->VoterMN,'VoterDOB'=>$result->date('m/d/Y', strtotime($result->VoterDOB)), 'Street'=>$result->Street, "VoterStatusID"=>$result->VoterStatusID,'phone'=>$result->phone);
        //fputcsv($output, $dataArray);
    }

    //OUPUT HEADERS
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
    header("Content-Transfer-Encoding: binary"); 

    //OUTPUT CSV CONTENT
    echo($csv); 
    exit();
}

我猜我需要使用下载助手+ force_download 功能,但我似乎无法获得它。有什么想法吗?

【问题讨论】:

    标签: php mysql codeigniter csv download


    【解决方案1】:

    我认为你有这么多标题,但更重要的是,如果文件是 CSV,为什么要将其作为二进制文件发送?你为什么不使用text/csv?我只使用下面的代码,我想Cache-Control是为了避免下载相同的文件而不打到服务器。无论如何,只有:

    header('Content-type: text/csv');
    header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
    

    应该可以。经过对 SO 的一些研究,根据您使用的浏览器,您的缓存标头可能存在问题: Creating and downloading CSV with PHP,所以研究一下,以避免未来的问题。

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2014-01-17
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多