0
我一直在PHP頁面上工作,將使用sqlsrv_fetch_array將一些SQL數據導出到csv文件。我在獲取csv文件中的數據時遇到了一些問題。當我運行腳本時,csv文件的輸出如下所示。sqlsrv使用PHP的csv
<html>
<head>
<title>Page Title</title>
</head>
<body>
" "
" "
"CCCCCCC\SSSSS" 140211 B Insxxxxxx BBB Y N CCCCCCC\SSSSS Stevens_Dave Y
CCCCCCC\SSSSS 140211 W Insxxxxxx BBB Y N CCCCCCC\SSSSS Stevens_Dave Y
CCCCCCC\SSSSS 140411 R Intxxxxx Auxxx BBB Y N CCCCCCC\SSSSS Stevens_Dave Y
注意,第一個「CCCCCC \ SSSS」仍然有「圍繞它,即使信息的休息不同時適用某種原因,它是在CSV文件的頂部張貼HTML的東西。我希望它把標題放在那裏,但似乎無法弄清楚如何讓它工作。你可以看看代碼,並讓我知道問題出在哪裏以及如何將標題添加到csv文件還有呢?下面是代碼。
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$userid = $_POST['userid']; //defined through a form
$serverName = "server1, 1433";
$connectionInfo = array("UID"=>"adminweb", "PWD"=>"adminweb", "Database"=>"dbname");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn === false)
{
echo "Could not connect.\n";
die(print_r(sqlsrv_errors(), true));
}
/* Set up and execute the query. */
$sql = "SELECT * FROM UserProfile u INNER JOIN UserTeam ut ON u.UserID = ut.UserOrTeam WHERE UserID LIKE '%xxxx%'";
$stmt = sqlsrv_query($conn, $sql);
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
foreach($row 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";
}
sqlsrv_free_stmt($results);
sqlsrv_close($conn);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=testcsv.csv");
echo $out;
?>
</body>
</html>