使用php(fputcsv函数)生成CSV文件时出现问题。 CSV文件数据很好,但格式化生成的文件的间隔在文件顶部有2个空行。不知道它来自哪里。有人可以帮忙吗?
的var_dump($头);给我下面。这里'x','x'是顶部的两个空白行。
x
x
array(16) {
[0]=>
string(14) "DataProviderID"
[1]=>
string(12) "DataProvider"
[2]=>
string(8) "FamilyID"
[3]=>
string(10) "FamilyName"
[4]=>
string(10) "SecurityID"
[5]=>
string(4) "Name"
[6]=>
string(10) "PrimaryRic"
[7]=>
string(13) "Administrator"
[8]=>
string(16) "IsAdminEULocated"
[9]=>
string(21) "IsAdminOnEsmaRegister"
[10]=>
string(25) "IsBenchmarkOnEsmaRegister"
[11]=>
string(26) "IsBenchmarkOnAdminRegister"
[12]=>
string(23) "HasEUListedFundTracking"
[13]=>
string(25) "HasEUListedFutureOrOption"
[14]=>
string(20) "IsAdminPre2016Active"
[15]=>
string(24) "IsBenchmarkPre2018Active"
}
DataProviderID DataProvider FamilyID FamilyName SecurityID Name PrimaryRic Administrator IsAdminEULocated IsAdminOnEsmaRegister IsBenchmarkOnEsmaRegister IsBenchmarkOnAdminRegister HasEUListedFundTracking HasEUListedFutureOrOption IsAdminPre2016Active IsBenchmarkPre2018Active
2 MSCI 36 MSCI Main Indices - Americas 17964 THE WORLD INDEX SMALL CAP-106230 .dMIWO000S0PUS MSCI Limited 1 1 0 99 99 99 99 0
2 MSCI 16730 MSCI Sector Indices - Europe Series 2 17996 EUROPE/OFFICE ELECTRONICS-106978 .dMIEU0OE00PUS MSCI Limited 1 1 0 99 99 99 99 0
我的代码如下:
<?php
require_once '../upload/functions.php';
$connectionInfo = getdb();
#$connectionInfo = sqlsrv_connect(DB_HOST, $connectionInfo);
if ($connectionInfo === false ) {
die (print_r(sqlsrv_errors(), true));
}
$sql = "SELECT * FROM <tablename>;";
$result = sqlsrv_query($connectionInfo, $sql);
if (!$result) die ('Couldn\'t fetch records');
$headers = array();
foreach (sqlsrv_field_metadata($result) as $fieldMetadata) {
$headers[] = $fieldMetadata['Name'];
}
#var_dump($headers);
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="KYBAttributes.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, array_values($headers),"\t");
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$row = str_replace('"', '', $row);
fputs($fp, implode("\t", $row)."\n");
}
die;
}
?>
请注意,关闭php标记'?&gt;'不是问题所在。
答案 0 :(得分:1)
您的源文件包含个人主页结束标记?>
,后跟换行符。 PHP需要完全重现<?
标记中未包含的所有行。因此,任何包含不需要的换行符的源文件都会在输出中产生换行符,因为这是您要求的换行符。