簡體   English   中英

下載csv文件

[英]download csv file

當我們點擊該按鈕時,我們有一個按鈕,所有數據都進入csv文件並下載此csv文件。 csv文件創建但下載代碼不起作用

$fp = fopen("file\customer-list.csv", "w");
fileName = "file\customer-list.csv";
$filePath = "file\customer-list.csv";
$fsize = filesize("file\customer-list.csv");

if(($_POST['csv_download_list']) == "cm")
{
    fwrite($fp, $csv);
    fclose($fp); 
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Disposition: attachment; filename=\"$fileName\"");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Length: ' . filesize($filePath));
    ob_clean();
    flush();
    $file = @fopen($filePath,"rb");
    if ($file) {
        while(!feof($file)) {
            print(fread($file, 1024*8));
            flush();
        }
    @fclose($file);
}
exit;

使用此代碼段應該執行您要執行的操作。

<?php

    $file = 'sample.csv'; //path to the file on disk

    if (file_exists($file)) {

        //set appropriate headers
        header('Content-Description: File Transfer');
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();

        //read the file from disk and output the content.
        readfile($file);
        exit;
    }
?>

您無需將文件保存到磁盤,只需在設置適當的標頭后回顯csv內容即可。 嘗試下面的代碼,它會更簡單

$fileName = 'customer-list.csv';

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

echo $csv;
exit;
Try...
function download($file) {
        if (!file_exists($file)) {
            return false;
        }
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit();
    }
$file = "file.csv";
download($file);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM