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;

}
4

1 回答 1

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

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

于 2013-06-26T14:08:09.273 回答