在PHP中将MySQL查询结果打印到CSV文件

在PHP中将MySQL查询结果打印到CSV文件,php,mysql,csv,Php,Mysql,Csv,我在使用php将MySQL查询结果写入文件时遇到问题。搜索肯定会有结果,文件也会被创建,但是当你打开文件时,它是空的。我认为这与我如何写入文件有关,但我不确定 $result = mysql_query($compsel); if(!result) die("unable to process query: " . mysql_error()); $fp = fopen('results.csv','w'); mysql_data_seek($result,0); //set data poin

我在使用php将MySQL查询结果写入文件时遇到问题。搜索肯定会有结果,文件也会被创建,但是当你打开文件时,它是空的。我认为这与我如何写入文件有关,但我不确定

$result = mysql_query($compsel);
if(!result) die("unable to process query: " . mysql_error());
$fp = fopen('results.csv','w');
mysql_data_seek($result,0); //set data pointer to 0
$rw = mysql_fetch_array($result, MYSQL_ASSOC);
print_r($rw);
foreach ($rw as $fields){
    fputcsv($fp, $fields);
}
fclose($fp);
提前谢谢

下面是一个例子:

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
您可以修改它以满足您的需要。 资料来源: