导出为CSV PHP作为下载文件

时间:2013-01-23 23:02:46

标签: php mysql fopen fputcsv

我正在使用CSV文件导出mysql表。如何直接将其存储在云端硬盘C:上,而无需任何通知

,我如何将其视为下载文件
<?php
$host = 'localhost'; // <--  db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His'); 

$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers    
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}


fputcsv($f, $items_array);
fclose($f);

?>

2 个答案:

答案 0 :(得分:0)

如果你想存储csv文件,然后在没有任何点击的情况下打开它,那就不可能了。

如果您只想打开它,请在浏览器窗口中通过

打开它
header('Content-disposition: inline;filename=foobar.csv');
header('Content-Type: text/csv;charset=UTF-8');
echo $csv_content;

其中$ csv_content是一个包含csv-file内容的字符串。你这样得到它

$csv_content = file_get_contents('c:/mycsv.csv');

答案 1 :(得分:0)

要下载它......

<?php
$host = 'localhost'; // <--  db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His'); 

$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers    
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}

fputcsv($f, $items_array);
fclose($f);

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="mycsv-{$timestamp}"');
readfile('C:/mycsv-{$timestamp}.csv');
?>

这仍然会通知用户下载,并且根据他们的设置,他们可能需要接受下载。当然不能覆盖此功能。