PHP从数据库导出CSV表

时间:2017-03-10 17:19:07

标签: php mysql csv

我是PHP的新手,我正在尝试做一个小实验来学习。

我想创建一行单词,单击它时,将从我在数据库中的表中下载csv文件。

到目前为止,这是我提出的(甚至不是我想做的。但我能够把它变成一个超链接)。

 echo "<a href=http://www.google.com>Click here to visit site</a>";

假设我已连接到我的数据库,我将如何连接“点击此处访问网站”以下载csv文件,例如,我的数据库ABC的table1?

我认为必须有一些循环读取table1中的行并将其写入csv文件,对吧?

1 个答案:

答案 0 :(得分:1)

创建一个具有以下代码的文件单独文件,并在当前文件中创建一个超链接,如:

echo "<a href='http://<your domain name>/test.php'>Click here to visit site</a>";

<?php 
 //test.php
// 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

$rows = mysqli_query($conn, 'SELECT name, email  FROM users limit 10');

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
?>
相关问题