2013-06-26 60 views
0

我試圖根據用戶選擇的報告輸出內容來動態生成CSV文件。檢索數據並使用CakeResponse將其寫入文件已完成,但是我努力將文件擴展名設置爲'.csv',文件以普通文本文件的形式下載。 CakePHP的文檔建議我這樣做:在CakeResponse中設置文件擴展名

$this->response->type('csv'); 

..但即使這是行不通的,我仍然得到一個文本文件。任何人都可以點亮一下嗎?請注意,我沒有尋找新的方法來生成CSV文件,我只是想改變擴展名。謝謝。

這是我下載的文件:

$this->response->body($this->constructFileBody($logs)); 

    return $this->response; 

這是方法「constructFileBody」,雖然我覺得它超出了這個問題的範圍:

public function constructFileBody($logs = array()){ 

    $content = ""; 
    for($i = 0; $i < count($logs); $i++){ 

     $row = $logs[$i]['EventLog']; 
     $line = $row['description'] . "," . $row['user'] . "," . $row['affected_user'] . "," . $row['report_title'] . "," . $row['date_created'] . "\n"; 

     $content = $content . $line; 
    } 

    return $content; 

} 
+0

顯示代碼您嘗試下載文件的方法 –

+0

我已經添加了該方法。 – kingLoosh

回答

1

,因爲我看到你的代碼,我不認爲你使用的任何地方標題,試試這個代碼:

//create a file 
$filename = "export_".date("Y.m.d").".csv"; 
$csv_file = fopen('php://output', 'w'); 

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

$results = $this->ModelName->query($sql); // This is your sql query to pull that data you need exported 
//or 
$results = $this->ModelName->find('all', array()); 

// The column headings of your .csv file 
$header_row = array("ID", "Received", "Status", "Content", "Name", "Email", "Source", "Created");//columns you want in csv file 
fputcsv($csv_file,$header_row,',','"'); 

// Each iteration of this while loop will be a row in your .csv file where each field corresponds to the heading of the column 
foreach($results as $result) 
{ 
// Array indexes correspond to the field names in your db table(s) 
$row = array(
    $result['ModelName']['id'], 
    $result['ModelName']['received'], 
    $result['ModelName']['status'], 
    $result['ModelName']['content'], 
    $result['ModelName']['name'], 
    $result['ModelName']['email'], 
    $result['ModelName']['source'], 
    $result['ModelName']['created'] 
); 

fputcsv($csv_file,$row,',','"'); 
} 

fclose($csv_file); 

現在看看你的代碼,並獲得需要替換的代碼行。

+0

雖然你有點太多了),我用了兩個標題行,它工作!謝謝! – kingLoosh

+0

它可能會起作用,但是從控制器動作發出頭文件(我認爲這是一個控制器動作)不是正確的做事方式。對於一個它使無法測試的代碼。 – AD7six