在CakeResponse中设置文件扩展名

时间:2013-06-26 13:40:26

标签: php cakephp cakephp-2.0

我正在尝试动态生成CSV文件,具体取决于用户选择的报告输出。检索数据并使用CakeResponse将其写入文件已完成,但是我很难将文件扩展名设置为“.csv”,文件作为普通文本文件下载。 CakePHP文档建议我这样做:

$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;

}

1 个答案:

答案 0 :(得分: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); 

现在查看您的代码并获取需要替换的代码行。