我是 PHP 新手,我正在尝试做一个小实验来学习。
我想创建一行单词,单击该行单词时,将从数据库中的表中下载 csv 文件。
到目前为止,这就是我所想出的(这甚至离我想要做的还很远。但我能够将其变成超链接)。
echo "<a href=http://www.google.com>Click here to visit site</a>";
假设我已经连接到数据库,我将如何连接“单击此处访问站点”以从数据库 ABC 的表 1 下载 csv 文件?
我认为必须有一些循环来读取 table1 中的行并将其写入 csv 文件,对吧?
最佳答案
创建一个包含以下代码的文件单独文件,并在当前文件中创建一个超链接,例如:
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);
?>
关于PHP 从数据库导出 CSV 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42724171/