在php中导出csv文件时出现问题

时间:2011-09-22 11:26:38

标签: php

我需要使用mysql查询在php中导出csv文件。但是当我导出像这样的文件“yourfilename.csv _”时。

我的代码是

header("Content-type: application/csv");

header("Content-Disposition: \"inline; filename=yourfilename.csv\"");  

$query = "SELECT * FROM login";

$result = mysql_query($query) ;

echo "username ,password \r\n";

while($row = mysql_fetch_array($result))
{
    echo "$row[user],$row[pass]\r\n";  
}  

我需要文件名“yourfilename.csv”。

1 个答案:

答案 0 :(得分:2)

您可以让MySql直接使用

将查询结果返回给文件
SELECT * INTO OUTFILE 'result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM my_table;

然后执行(also see Example #1 Download dialog)

header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="yourfilename.csv"');
readfile('result.csv');