经过大量的搜索和修改之后,我成功地将表导出到.csv文件中,但现在我想通过浏览器启动下载,而不是自动存储在文件夹中。
这是我的密码:
<?php
$server = 'localhost';
$user = 'root';
$pass = 'pass';
$db = 'test';
$db = mysqli_connect($server, $user, $pass, $db);
mysqli_set_charset($db, "utf8");
$filename = 'uploads/'.strtotime('now').'.csv';
$fp = fopen($filename,"w");
$query = "SELECT id,product,status,created,summary FROM product_table";
$result = mysqli_query($db,$query) or die( "My query ($query) generated an error: ".mysql_error());
$row = mysqli_fetch_assoc($result);
$seperator = "";
$comma = "";
foreach ($row as $name => $value){
$seperator.= $comma. ''.str_replace('','""',$name);
$comma=",";
}
$seperator .= "\n";
echo $seperator;
//putting the heading into the csv file
fputs($fp,$seperator);
mysqli_data_seek($result,0);
while ($row = mysqli_fetch_assoc($result)){
$seperator = "";
$comma = "";
foreach ($row as $name => $value){
if (strcmp($name,'summary') == 0){
$value = str_replace( array( "\r" , "\n", "\r\n", "\n\r" ) ,'' , $value);
$value = str_replace('</b><br>','',$value);
$value = str_replace('<b>','',$value);
$value = str_replace('<br>','',$value);
$value = str_replace('<br />','',$value);
}
$seperator.= $comma. ''.str_replace('','""',$value);
$comma=",";
}
$seperator .= "\n";
//putting the heading into the csv file
fputs($fp,$seperator);
}
fclose($fp);
?>运行上述脚本将.csv文件存储在上传文件夹中。为了使用户能够运行脚本并通过浏览器下载.csv文件,我需要做哪些更改来启用浏览器下载?谢谢!
编辑:此外,如果想禁用对文件夹的保存,并且只允许用户/浏览器下载,我还需要做哪些修改?谢谢。
发布于 2012-12-09 09:11:29
试着用这个:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=your_file.csv');
header('Pragma: no-cache');
readfile($filename);发布于 2013-05-05 13:59:44
当然,表标题出现了两次,因为这一行在不同地方的代码中出现了两次:
//putting the heading into the csv file
fputs($fp,$seperator);发布于 2013-11-15 02:27:06
我认为以下两行足以迫使浏览器自动下载csv文件
标题(“内容-类型:文本/csv”);标题(“内容-处理:附件;filename=”“dishes.csv”);
其中文件名-指定名称csv文件名
https://stackoverflow.com/questions/13786093
复制相似问题