php 从 mysql 导出 csv

标签 php mysql

我有脚本应该从数据库中导出 .csv 文件。问题是它会将导出保存到特定的 ($f) 文件,但不会下载正确的文件(脚本下载空文件)

    <?php
//load the database configuration file
include '../secure/db_connect.php';

//get records from database

$sql_list = "SELECT * FROM `hakom` ORDER BY id DESC";
$sql_list_result = $mysqli->query($sql_list);



if($sql_list_result->num_rows > 0){
    $delimiter = ",";
    $filename = "members_" . date('Y-m-d') . ".csv";

    //create a file pointer
    $f = fopen('hakom_export.csv', 'w');

    //set column headers
    $fields = array('ID', 'MSISDN_');
    fputcsv($f, $fields, $delimiter);

    //output each row of the data, format line as csv and write to file pointer
    while($row = $sql_list_result->fetch_assoc()){

        $lineData = array($row['ID'], $row['MSISDN_']);
        fputcsv($f, $lineData, $delimiter);
    }

    //move back to beginning of file
    fseek($f, 0);

    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    //output all remaining data on a file pointer
    fpassthru($f);
}
exit;

?>

我遵循 this page 上的教程

最佳答案

您以只写方式打开文件...

$f = fopen('hakom_export.csv', 'w');

来自 fopen 手册页...

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

将模式改为w+

$f = fopen('hakom_export.csv', 'w+');

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

关于php 从 mysql 导出 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49953968/

相关文章:

PHP - 外部类/库可以从 apache 访问,但不能从 phpunit 访问

php - 如何在 PHP 脚本中将表与其自身连接起来进行查询,并告诉脚本从哪个表中选择哪一列?

php - 使用 echo 显示表中的前 100 个字符

mysql - 媒体库 MySql 数据库设计

php - 在 1 个数据库列中更新多个结果

php - 用户可以使用直接链接访问 protected 页面。如何创建重定向?

javascript - 当时钟到达 '0' 时停止 JavaScript 定时器

php - 结果是小数吗?

mysql - 在 2 个表之间进行连接的选择期间 where 子句中的分配顺序

php - 如何从 Laravel MySQL 循环条件聚合中检索关于 $row 数据的 $key?