Php 在CakerResponse中设置文件扩展名

Php 在CakerResponse中设置文件扩展名,php,cakephp,cakephp-2.0,Php,Cakephp,Cakephp 2.0,我正在尝试动态生成一个CSV文件,这取决于用户选择什么作为报告输出。使用CakerResponse检索数据并将其写入文件已经完成,但是我很难将文件扩展名设置为“.csv”,该文件将作为普通文本文件下载。 CakePHP文档建议我这样做: $this->response->type('csv'); …但即使这不起作用,我仍然得到一个文本文件。有人能解释一下吗?请注意,我不是在寻找生成CSV文件的新方法,我只是想更改扩展名。多谢各位 以下是我下载文件的方式: $this->res

我正在尝试动态生成一个CSV文件,这取决于用户选择什么作为报告输出。使用CakerResponse检索数据并将其写入文件已经完成,但是我很难将文件扩展名设置为“.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;

}
公共函数constructFileBody($logs=array()){
$content=“”;
对于($i=0;$i
当我看到您的代码时,我认为您没有在任何地方使用标题,请尝试以下代码:

//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); 

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

向代码显示您尝试下载该文件的方法我添加了该方法。尽管您给出了太多;),我使用了两个标题行,效果很好!!非常感谢。它可能会工作,但从控制器操作(我假设它是控制器操作)发出头不是正确的方法。首先,它生成了不稳定的代码。