我正在使用Yii 1框架。我尝试将表详细信息下载为.csv文件,并使用ID从表中检索数据。
单击按钮时,它将检索数据并显示在inspect元素的Network部分中。没有错误,只有问题是不下载文件。
这是控制器方法的代码。
public function actionDownload()
{
$id = $_REQUEST['id'];
$vote_record = Vote::model()->findByAttributes(array('id' => $id));
$name = $vote_record['name'];
header('Content-Description: File Transfer');
header("Content-type: application/csv");
header('Content-Disposition: attachment; filename="'. str_replace(" ", "_", strtolower($name)) . '_results.csv"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
$titile = "Option, Vote Count\n";
echo $titile;
if (count($vote_record) > 0) {
echo $vote_record['name'] . "," . $vote_record['total'] . "\n";
echo "\n\n";
echo $vote_record['opname1'] . "," . $vote_record['voteCount1'] . "\n";
echo $vote_record['opname2'] . "," . $vote_record['voteCount2'] . "\n";
echo $vote_record['opname3'] . "," . $vote_record['voteCount3'] . "\n";
echo $vote_record['opname4'] . "," . $vote_record['voteCount4'] . "\n";
}
}
所以请帮助解决这个问题。
答案 0 :(得分:0)
您可以针对您的问题尝试此解决方案:
<?php
public function actionDownload() {
$id = $_REQUEST['id'];
$vote_record = Vote::model()->findByAttributes(array('id' => $id));
$name = $vote_record['name'];
header("Content-type: application/csv");
header('Content-Disposition: attachment; filename="'. str_replace(" ", "_", strtolower($name)) . '_results.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
if (count($vote_record) > 0) {
fputcsv($handle, array('Option', 'Vote Count'));
fputcsv($handle, array($vote_record['name'], $vote_record['total']));
fputcsv($handle, array($vote_record['opname1'], $vote_record['voteCount1']));
fputcsv($handle, array($vote_record['opname2'], $vote_record['voteCount2']));
fputcsv($handle, array($vote_record['opname3'], $vote_record['voteCount3']));
fputcsv($handle, array($vote_record['opname4'], $vote_record['voteCount4']));
fclose($handle);
exit;
}
ob_clean();
flush();
}
?>
我希望它会有所帮助。