通过php将mysql数据导出到.csv的问题

时间:2012-07-14 03:43:47

标签: php export-to-csv

我使用以下方法尝试将数据导出到csv文件,我使用的methoid来自以下链接Problem in Export csv file in php,但是当我尝试导出文件时,系统回复我没有这样的文件可以读取,所以我想问我必须在执行代码之前先打开一个result.csv吗?或者文件result.csv已经生成,但是在错误的目录中,如果这是原因,请问如何定义应该在其中创建文件的目录。

$result = mysql_query("SELECT TechName, ClientName, SiteName, Time, Type
                            INTO OUTFILE 'result.csv'
                            FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED by '\"'
                            LINES TERMINATED BY '\n'
                            FROM Tech AS T, Client AS C, Site AS S, Log AS L
                            WHERE T.TechID=L.TechID AND C.ClientID=L.ClientID AND S.SiteID=L.SiteID
                            ORDER BY L.Time DESC");
    $Time = date('Y_m_d_H_i');
    $fileName = "Report_".$Time.".csv";
    header('Content-type: text/csv'); 
    header('Content-Disposition: attachment; filename="'.$fileName.'"'); 
    readfile('result.csv');

2 个答案:

答案 0 :(得分:1)

试试这段代码可能会。在这里找到它:http://salman-w.blogspot.in/2009/07/export-mysql-data-to-csv-using-php.html

<?php
/*
 * PHP code to export MySQL data to CSV
 * http://salman-w.blogspot.com/2009/07/export-mysql-data-to-csv-using-php.html
 *
 * Sends the result of a MySQL query as a CSV file for download
 */

/*
 * establish database connection
 */

$conn = mysql_connect('MYSQL_HOST', 'MYSQL_USERNAME', 'MYSQL_PASSWORD') or die(mysql_error());
mysql_select_db('MYSQL_DATABASE', $conn) or die(mysql_error($conn));

/*
 * execute sql query
 */

$query = sprintf('SELECT * FROM MYSQL_TABLE');
$result = mysql_query($query, $conn) or die(mysql_error($conn));

/*
 * send response headers to the browser
 * following headers instruct the browser to treat the data as a csv file called export.csv
 */

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');

/*
 * output header row (if atleast one row exists)
 */

$row = mysql_fetch_assoc($result);
if ($row) {
    echocsv(array_keys($row));
}

/*
 * output data rows (if atleast one row exists)
 */

while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}

/*
 * echo the input array as csv data maintaining consistency with most CSV implementations
 * - uses double-quotes as enclosure when necessary
 * - uses double double-quotes to escape double-quotes 
 * - uses CRLF as a line separator
 */

function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}
?>

答案 1 :(得分:0)

如果您尝试输出查询结果,只需执行此操作即可。根本不需要readfile()。您所需要的只是您已有的标题,以及输出CSV数据的内容。

另请注意,您只需使用fputcsv()将数组格式化为CSV行即可。 http://php.net/manual/en/function.fputcsv.php