经过大量的谷歌搜索和修补,我设法将表导出到.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文件?谢谢!
修改 此外,如果想要禁用保存到文件夹并仅启用用户/浏览器下载,我还需要进行哪些修改?感谢。
答案 0 :(得分:4)
试试这个:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=your_file.csv');
header('Pragma: no-cache');
readfile($filename);
答案 1 :(得分:1)
表格标题肯定会出现两次,因为这一行在不同地方的代码中出现两次:
//putting the heading into the csv file
fputs($fp,$seperator);
答案 2 :(得分:0)
我认为以下两行足以迫使浏览器自动下载csv文件
header('Content-Type:text / csv'); header('Content-Disposition:attachment; filename =“dishes.csv”');
其中filename - 给出名称csv文件名