2012-01-17 106 views
0

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

<?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; 

?> 

回答

0

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

出。= “COL01,col02,col03,col04,col05,col06,col07 \ n”

+0

我认为这会工作,我使它静态。我实际上是在编写它,以便我可以在不同的表上使用相同的代码。 – klcant 2012-01-18 15:55:00