【问题标题】:export mysql table data to csv file through php..html also get dumped通过 php..html 将 mysql 表数据导出到 csv 文件也会被转储
【发布时间】:2014-10-27 17:44:48
【问题描述】:

所以我试图通过 php 将 mysql 表导出到 csv 文件。这是代码

<?php if (isset($_POST['exp'])) {

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

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

    fputcsv($output, array('User ID', 'User Name', 'Password'));
    $con = mysqli_connect('localhost', 'root', 'pass', 'xyz');
    $rows = mysqli_query($con, 'SELECT * FROM users');

    while ($row = mysqli_fetch_assoc($rows)) {
      fputcsv($output, $row);
    }
    fclose($output);
    mysqli_close($con);
  }
?>

<div>
  <form action="#" method="post">
    <input type="submit" value="Export" name="exp" />
  </form>
</div>

一切都很好,但 html 部分也被转储到 csv 文件中。这是csv的屏幕截图

为什么会这样?我做错什么了吗?

【问题讨论】:

  • 将您的代码分成两个不同的文件:HTMLPHP

标签: php mysql csv mysqli


【解决方案1】:

您的页面在 PHP 之外继续加载。在 IF 语句的末尾添加exit(),它将立即停止运行。

<?php if (isset($_POST['exp'])) {

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

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

    fputcsv($output, array('User ID', 'User Name', 'Password'));
    $con = mysqli_connect('localhost', 'root', 'pass', 'xyz');
    $rows = mysqli_query($con, 'SELECT * FROM users');

    while ($row = mysqli_fetch_assoc($rows)) {
      fputcsv($output, $row);
    }
    fclose($output);
    mysqli_close($con);
    exit();
  }
?>

<div>
  <form action="#" method="post">
    <input type="submit" value="Export" name="exp" />
  </form>
</div>

【讨论】:

  • 好的,这就行了。但是为什么即使我关闭了文件指针,html 也会被写入 csv?
  • 我的猜测是因为关闭文件指针后脚本继续执行。因此,即使文件指针关闭,之后仍存在更多输出,即 HTML。所以它只是被标记到它的末尾。
猜你喜欢
  • 2011-12-04
  • 1970-01-01
  • 2023-01-19
  • 2015-06-10
  • 1970-01-01
  • 2023-03-10
  • 2014-10-20
相关资源
最近更新 更多