0

如何在 PHP 中做到这一点?

我不想只导出 csv 文件中的表数据并将 csv 文件存储在备份文件夹中。

为此我正在使用这个:

$query = "SELECT * FROM `login_details`";
$file_name = "login_details";
$sql_csv = mysql_query($query) or die("Error: " . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer

header("Content-type:text/octect-stream");
$done = header("Content-Disposition:attachment;filename=$fileName");

while($row = mysql_fetch_row($sql_csv)) {
     print '"' . stripslashes(implode('","',$row)) . "\"\n";
}

谢谢。

4

3 回答 3

0

您必须打开文件才能写入(处理)使用http://php.net/manual/en/function.fopen.php

使用创建的句柄编写字符串http://php.net/manual/en/function.fputcsv.php

完成后关闭句柄(参见 fopen 文档)使用 fclose()

例如:

//you code to get data from sql
$handle = fopen('full path to store (you can use ftp etd)', 'w'); // see mode
while($row = mysql_fetch_row($sql_csv)) {
     fputcsv($handle, $row);
}
fclose($handle);
于 2013-07-22T08:04:44.767 回答
0

如果您的备份文件夹位于(或可以位于)运行 MySql 的同一台机器上,那么实现目标的最快和最简单的方法是使用SELECT ... INTO OUTFILE子句

SELECT * 
  FROM login_details
  INTO OUTFILE '/path/to/backup/folder/login_details.csv' 
       FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
       LINES TERMINATED BY '\n' -- or \r\n

php代码

$sql = "SELECT * 
          FROM login_details
          INTO OUTFILE '/path/to/backup/folder/login_details.csv' 
               FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
               LINES TERMINATED BY '\n'";
$result = mysql_query($sql);
if (!$result) {
   die('Error: ' . mysql_error()); //TODO better error handling
}

附带说明:mysql_*不推荐使用扩展名。考虑切换到 mysqli 或 PDO。

于 2013-07-22T08:10:24.213 回答
0

您可以使用fputcsv来执行此操作。这里是功能手册: http: //php.net/manual/en/function.fputcsv.php

$query = "SELECT * FROM `login_details`";
$file_name = "login_details";
$sql_csv = mysql_query($query) or die("Error: " . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer

$fp = fopen('cvsfile.csv', 'w');
while($row = mysql_fetch_row($sql_csv)) {
     fputcsv($fp, split(',', $row));
}
fclose($fp);
于 2013-07-22T08:10:45.340 回答