0

我使用以下方式尝试将数据导出到 csv 文件,我使用的方法来自以下链接Problem in Export csv file in php,但是当我尝试导出文件时,系统回复我 no such file can被阅读,所以我想问在执行代码之前我必须先打开一个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');
4

2 回答 2

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";
}
?>
于 2012-07-14T03:48:48.083 回答
0

如果您尝试输出查询结果,只需这样做。readfile()根本不需要。您只需要已有的标题,以及输出 CSV 数据的东西。

另请注意,您可以简单地fputcsv()将数组格式化为 CSV 行。 http://php.net/manual/en/function.fputcsv.php

于 2012-07-14T03:45:56.597 回答