Php 使用CodeIgniter下载结果的CSV

Php 使用CodeIgniter下载结果的CSV,php,mysql,codeigniter,csv,download,Php,Mysql,Codeigniter,Csv,Download,我们使用CodeIgniter对MySQL数据库运行查询,并在页面上显示这些结果。有时,我们希望将其作为CSV下载。我前面的那个家伙设置了这个下载按钮,但它根本不起作用。从来没有 这是下载的现有代码: public function download_csv_search(){ $dbresults = $this->do_search(); $results = $dbresults['results']; $csv = "First Name, Last N

我们使用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();
}

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

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

header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
应该有用。在SO中进行一点研究后,根据您使用的浏览器,您的缓存头可能会出现问题: ,所以研究一下,以避免未来的问题