我是PHP新手,我正在尝试创建一小段代码,用于读取数据库中的表格,并允许用户将表格下载到CSV文件中。
到目前为止,我已经能够连接到我的数据库并通过表格回显
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed1: " . $conn->connect_error);
}
// SQL query
$sql = "SHOW TABLES IN `abc1`";
// perform the query and store the result
$result = $conn->query($sql);
// if the $result not False, and contains at least one row
if($result !== false) {
// if at least one table in result
if($result->num_rows > 0) {
// traverse the $result and output the name of the table(s)
while($row = $result->fetch_assoc()) {
echo '<br />'. $row['Tables_in_abc1'];
}
}
else echo 'There is no table in "tests"';
}
else echo 'Unable to check the "tests", error - '. $conn->error;
$conn->close();
?>
现在我想将每个表格变成一个链接,这样当用户点击它时,他们就可以将表格的数据下载到CSV文件中。
我该怎么做?
答案 0 :(得分:2)
这应该是一个评论,但我没有足够的水平留下一个。你应该看看PHPExcel。
https://github.com/PHPOffice/PHPExcel
它附带了许多例子,可以帮助你实现你想要做的事情。
答案 1 :(得分:2)
您可以将数据流式传输到客户端,如下所示:
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=file.csv');
$stdout = fopen('php://stdout', 'w');
while($row = $result->fetch_assoc()) {
fputcsv($stdout, $row);
}
fclose($stdout);
或写入文件:
$filePath = __DIR__ .'/tmp.csv'; // for instance current folder
$fh = fopen($filePath, 'w+');
while($row = $result->fetch_assoc()) {
fputcsv($fh, $row);
}
fclose($fh);
然后将find发送给客户端:
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=file.csv');
readfile($filePath);