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

时间:2012-01-17 20:16:01

标签: php sql-server-2008 csv

我使用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;

?>

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

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

out。=“col01,col02,col03,col04,col05,col06,col07 \ n”