如何将mysql表导出到csv文件并下载

时间:2011-06-09 14:30:18

标签: php drupal

我试图从mysql将数据导出到csv文件。我使用了以下脚本,但$ result变量有错误:mysql_num_fields告诉提供的参数无效

$filename = 'myfile.csv';
$result = db_query("SELECT * FROM {loreal_salons}");


drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++) {
    $header[] = mysql_field_name($result, $i);
}
print implode(',', $header) . "\r\n";

while ($row = db_fetch_array($result)) {
    foreach ($row as $value) {
        $values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
    }
    print implode(',', $values) . "\r\n";
    unset($values);
}

1 个答案:

答案 0 :(得分:4)

如果您不介意使用临时文件,可以执行以下操作:

SELECT *
INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM loreal_salons

作为您的查询,然后只需执行:

header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();