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