我在使用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);
提前致谢!
答案 0 :(得分:1)
以下是一个例子:
// 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);
您可以根据自己的需要进行修改。 资料来源:http://code.stephenmorley.org/php/creating-downloadable-csv-files/