使用PHP将带有标题的SQL Server表导出为CSV


Export SQL Server table with headers to CSV using PHP

我正在使用php将SQL Server表导出到CSV(请参阅下面的代码)。我需要帮助的是在导出中包含列的标题。当我从MySQL导出时,我可以做到这一点,但无法用SQL Server解决。如果有人能为我指明正确的方向,我将不胜感激

<?php
// SQL Server connection string details.
    $myServer = "server";
    $myUser = "user";
    $myPass = "password";
    $myDB = "dbname";
// connection to the SQL Server
    $dbhandle = mssql_connect($myServer, $myUser, $myPass)
            or die("Couldn't connect to SQL Server on $myServer"); 
//select a database to work with
        $selected = mssql_select_db($myDB, $dbhandle)
            or die("Couldn't open database $myDB"); 
//declare the SQL statement that will query the database
        $query = "SELECT col01, col02, col03, col04, col05, col06, col07 ";
        $query .= "FROM table ";
        $result = mssql_query($query, $dbhandle);
//Generate CSV file - Set as MSSQL_ASSOC as you don't need the numeric values.
    while ($l = mssql_fetch_array($result, MSSQL_ASSOC)) {
    foreach($l AS $key => $value){
        //If the character " exists, then escape it, otherwise the csv file will be invalid.
            $pos = strpos($value, '"');
            if ($pos !== false) {
                $value = str_replace('"', ''"', $value);
            }
            $out .= '"'.$value.'",';
    }
    $out .= "'n";
    }
//free result set memory
    mssql_free_result($result);
//close the connection
    mssql_close($dbhandle);
// Output to browser with the CSV mime type
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=export.csv");
    echo $out;
?>

使用http://php.net/manual/en/function.mssql-fetch-field.php,如下所示:http://www.razorsql.com/articles/sqlserver_column_names_values.html

在迭代请求结果之前,将col01、col02、col03、col04、col05、col06、col07添加到$out变量的第一行将解决问题

退出="col01,col02,col03,col04,col05,col06,col07''n"