[英]Export SQL Server table with headers to CSV using PHP
I am exporting a SQL Server table to a CSV using php (see code below). 我正在使用php将SQL Server表导出到CSV(请参见下面的代码)。 What I am needing help with is including the headers of the columns in the export.
我需要帮助的是在导出中包括各列的标题。 I can do this when I export from MySQL, but cannot figure it out with SQL Server.
从MySQL导出时可以执行此操作,但无法通过SQL Server弄清楚。 If anyone can point me in the right direction I would appreciate it.
如果有人能指出正确的方向,我将不胜感激。
<?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;
?>
Adding col01, col02, col03, col04, col05, col06, col07 to the first line of your $out variable before iterating through you request results will solve your problem 在迭代请求结果之前,将col01,col02,col03,col04,col05,col06,col07添加到$ out变量的第一行将解决您的问题
out .="col01, col02, col03, col04, col05, col06, col07\\n" out。=“ col01,col02,col03,col04,col05,col06,col07 \\ n”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.