php从mysql导出csv

时间:2018-04-21 08:47:18

标签: 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

上的教程

2 个答案:

答案 0 :(得分:0)

您打开文件只写...

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

来自fopen手册页...

  

&#39; W&#39;仅供写作;将文件指针放在开头   该文件并将文件截断为零长度。如果文件没有   存在,试图创造它。

将模式更改为w +

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

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

答案 1 :(得分:0)

试试这段代码。

  <?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);


?>