从php生成器格式化csv文件

从php生成器格式化csv文件,php,csv,Php,Csv,我得到了一个从sql查询创建cvs文件的函数 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' );

我得到了一个从sql查询创建cvs文件的函数

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…)

默认情况下
fputcsv
使用逗号作为分隔符,而Excel需要分号分隔符,那就太好了。 您可以通过将分号分隔符作为第三个参数添加到
fputcsv
函数来修改函数,以获得“正确”的excel 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);
    }

万岁excel,你不能只是打开一个csv文件(再),你必须导入它。只有这样,它才会正确显示。您需要知道,您的基本csv阅读器(如Microsoft Excel或Open Office Excel…)会注意到csv的第一行作为标题。因此,您基本上只需这样放置文件:
$csv=“A1;B1;\r2014-10-30;3333334;\r2011-11-12;576666;”等…请不要再维护它们,它们将被删除。而是学习,并使用或。这将帮助你做出决定。