【问题标题】:PHP echo tables in a database and download them as CSV files数据库中的 PHP 回显表并将它们下载为 CSV 文件
【发布时间】:2017-03-09 23:04:25
【问题描述】:

我是 PHP 新手,我正在尝试创建一个小的 sn-p 代码来读取我数据库中的表并允许用户将表下载到 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 文件中。

我该怎么做?

【问题讨论】:

    标签: php database csv hyperlink


    【解决方案1】:

    这应该是一个评论,但我的水平还不够高,不能留下评论。你应该看看 PHPExcel。

    https://github.com/PHPOffice/PHPExcel

    它附带了许多示例,可以帮助您实现您想要做的事情。

    【讨论】:

    【解决方案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); 
    

    然后将查找结果发送给客户端:

    header('Content-type: text/csv');
    header('Content-disposition: attachment;filename=file.csv');
    
    readfile($filePath);
    

    http://php.net/manual/en/function.fputcsv.php

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 1970-01-01
      • 2018-11-19
      • 2013-11-24
      • 2015-09-10
      • 2016-11-11
      • 2014-12-29
      • 2020-05-27
      • 1970-01-01
      相关资源
      最近更新 更多