PHP CSV導出功能,文件輸出到客戶端

直接上代碼

public function doExcel($data)
{
    // 文件名
    $filename = date('YmdHis') . '.csv';
    // 文件完整路徑
    $filepath = dirname(dirname(__FILE__)) . '/' . $filename;
    // 打開文件,沒有自動創建
    $fp = fopen($filepath, 'a');

    // 設置導航欄
    $headers = array('手機號','地市');
    $content = implode(',', $headers) . PHP_EOL;
    // 填充數據
    foreach ($data as $value) {
        $content .= $value['phone'] . ',' . $value['name'] . PHP_EOL;
    }

    // 寫入數據
    fwrite($fp, $content);
    // 關閉文件
    fclose($fp);

    // 設置header
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename='.$filename);
    header("Content-Transfer-Encoding:binary");

    // 輸出到瀏覽器
    readfile($filepath);
    // 刪除本地文件
    unlink($filepath);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章