php从mysql导出csv

xjreopfe  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(364)

我有脚本,应该从数据库导出.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;

?>

我遵循本页的教程

f2uvfpb9

f2uvfpb91#

正在打开文件以进行只写操作。。。

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

从fopen手册页。。。
“w”仅用于书写;将文件指针放在文件的开头,并将文件截断为零长度。如果文件不存在,请尝试创建它。
将模式更改为w+

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

“w+”开放阅读和写作;将文件指针放在文件的开头,并将文件截断为零长度。如果文件不存在,请尝试创建它。

oaxa6hgo

oaxa6hgo2#

试试这个代码。

<?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
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

?>

相关问题