如何用php导出sql数据的csv文件?

时间:2015-07-20 23:26:16

标签: php mysql csv

我目前有一个应用程序,显示大约4,000个项目。我从mysql数据库中提取这个。我正在尝试创建一个按钮,强制将数据库中的所有项目下载到csv文件中。我怎么能这样做呢?

csv.php

<?php

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

$output = fopen('php://output', 'w');

fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

mysql_connect('localhost', 'root', 'root');
mysql_select_db('wp_xroads');
$rows = mysql_query('SELECT first_name,last_name,phone FROM bags');

while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
?>

HTML

<div class="col-md-2">
  <!-- Button to trigger csv file exporting -->
    <form action="csv.php" method="get">
        <a class="btn btn-success" type="submit" target="_blank">
          Export CSV <span class="badge"><span class='glyphicon glyphicon-save-file'></span></span>
        </a>
    </form>
</div>
提前谢谢。 -Ken

1 个答案:

答案 0 :(得分:2)

SELECT INTO OUTFILELOAD DATA FILE相反。这会将select语句的结果放入指定的文件中。没有慢,zanny,非高性能的PHP循环。 export_options子句与LOAD DATA INFILE中的选项具有相同的风格。

https://dev.mysql.com/doc/refman/5.1/en/select-into.html

SELECT col1,col2,col3 INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;


SELECT first_name,last_name,phone INTO OUTFILE '/tmp/myBags.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM bags;