-1
我有一個函數可以從sql查詢創建一個cvs文件。從php生成器格式化csv文件
function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query, $db_conn) or die(mysql_error($db_conn));
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
}
的事情是,生成的文件看起來像這樣
A1 | B1
2014-10-30,333333333333333333333334
我怎麼能拆分的日期是在A1和B2中的數字?這將是很好,如果我也可以命名我的標題(A1到Date ..)
萬歲Excel中,你不能只是打開一個CSV文件(再)你必須導入它。只有這樣它才能正確顯示。 – 2014-11-03 12:53:55
您需要知道您的基本csv閱讀器(如Microsoft Excel或Open Office Excel,...)會注意到您的csv的第一個「行」作爲標題。所以你基本上只需要把你的文件寫成這樣:'$ csv =「A1; B1; \ r2014-10-30; 3333333334; \ r2011-11-12; 576666;」;'etc ... – 2014-11-03 13:17:10
請[不要使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php),它們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。學習[準備的語句](http://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。 [本文](http://php.net/manual/en/mysqlinfo.api.choosing.php)將幫助你決定。 – 2014-11-03 13:41:45