0

经过一番谷歌搜索和修改后,我设法将表格导出到 .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 文件存储在文件夹 uploads 中。我需要进行哪些更改才能启用浏览器下载,以便用户可以运行脚本并通过浏览器下载 .csv 文件?谢谢!

编辑: 此外,如果要禁用保存到文件夹并仅启用用户/浏览器下载,我必须进行哪些修改?谢谢。

4

3 回答 3

4

试试这个:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=your_file.csv');
header('Pragma: no-cache');
readfile($filename);
于 2012-12-09T09:11:29.887 回答
1

表标题肯定会出现两次,因为这一行在不同位置的代码中出现了两次:

//putting the heading into the csv file
fputs($fp,$seperator);
于 2013-05-05T13:59:44.507 回答
0

i think following two lines enough to force browser to auto download csv file

header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="dishes.csv"');

where filename -- give name name csv file name

于 2013-11-15T02:27:06.150 回答