2016-10-04 131 views
-1

我想要生成,然後默認使用PHP腳本下載csv文件。我有在鉻和Internet Explorer工作正常的代碼,但相同的腳本不適用於Firefox。在Firefox腳本不會正確生成CSV文件。以下是腳本firefox無法下載csv文件

require('core.php'); 
$master = new db(); 
$s = $master->getRecords(); 
function array2csv(array &$array) 
{ 
    if (count($array) == 0) { 
    return null; 
    } 
    ob_start(); 
    $df = fopen("php://output", 'w'); 
    fputcsv($df, array_keys(reset($array))); 
    foreach ($array as $row) { 
     fputcsv($df, $row); 
    } 
    fclose($df); 
    return ob_get_clean(); 
} 

function download_send_headers($filename) { 

    // disable caching 
    $now = gmdate("D, d M Y H:i:s"); 
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); 
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); 
    header("Last-Modified: {$now} GMT"); 

    // force download 
    header("Content-Type: application/force-download"); 
    header("Content-Type: application/octet-stream"); 
    header("Content-Type: application/download"); 


    // disposition/encoding on response body 
    header("Content-Disposition: attachment;filename={$filename}"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Disposition: attachment;filename={$filename}"); 
    header("Content-Transfer-Encoding: binary"); 
} 
download_send_headers(site_title .' '. date("d M Y") . ".csv"); 
echo array2csv($s); 
die(); 

HTML和JS

<a class="list-group-item" href="javascript:void(0);" onclick="return exportUser();">Export to CSV</a> 

function exportUser(){ 
     $.ajax({ 
     url: 'get_csv.php', 
     type: 'POST', 
     success: function() { 
      window.location = 'get_csv.php'; 
     } 
    }); 
} 

我還附上了理解的屏幕截圖。 enter image description here

+0

*「在Firefox腳本沒有產生csv文件正確。「* ...以什麼方式? – CD001

+0

@ CD001相同的代碼在Chrome和IE中工作正常,它正在生成CSV文件並下載,但是相同的腳本在Firefox中不起作用。 –

+1

根本不會生成CSV文件(不會提取下載對話框)或在屏幕上生成它,或者以某種方式生成它不正確,因此它不是有效的CSV? – CD001

回答

0

嘗試增加這個頭:

header('Content-Type: application/csv; charset=utf-8'); 
+0

而不是哪個? –

+0

你可以嘗試刪除應用程序/下載並添加它,看看它是否工作 –

+0

我檢查了它,不工作 –

0

您需要將事件添加到您的js函數

功能exportUser(事件)會做

+0

請解釋一下,我不明白 –

+0

你目前調用你的函數就像這個「function exportUser()」,但是因爲它是Mozilla Firefox它不起作用,因爲你沒有發送任何事件。你需要像這樣調用你的函數「function exportUser(event)」 – ptk