[英]php export csv from 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;
?>
我遵循此页面上的教程
您打开的文件仅供写...
$f = fopen('hakom_export.csv', 'w');
从fopen手册页...
w只开放写作; 将文件指针放在文件的开头,并将文件截断为零长度。 如果该文件不存在,请尝试创建它。
将模式更改为w +
$f = fopen('hakom_export.csv', 'w+');
'w +'开放供阅读和写作; 将文件指针放在文件的开头,并将文件截断为零长度。 如果该文件不存在,请尝试创建它。
试试这个代码。
<?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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.