gpt4 book ai didi

php - 获取csv文件中的列名

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:37 24 4
gpt4 key购买 nike

正在创建 CSV 文件并想知道如何在第一行中获取列名。现在我认为它正在尝试回应列名但得到 0'nulls。我也想知道是否可以将每个值放在每个单元格中,我可以在 excel 中手动完成,但这很麻烦。

enter image description here

这是代码:

$result=sqlsrv_query($conn,$sql) or die("Couldn't execute query:<br>" . sqlsrv_error(). "<br>" . sqlsrv_errno()); 

$file_ending = "csv";
$reals=array();
//header info for browser
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character

$i=0;
foreach( sqlsrv_field_metadata( $result ) as $fieldMetadata ) {
echo $fieldMetadata["Name"]+"\t";
if($fieldMetadata["Type"]=="real")//$fieldMetadata["Type"]=== SQL_REAL
{
$reals[] = $i;
}
$i++;
}


print("\n");
//end of printing column names
//start while loop to get data
while($row = sqlsrv_fetch_array($result))
{

$schema_insert = "";
for($j = 0; $j < sqlsrv_num_fields($result); $j++)
{
if ($row[$j] != "") {
if (in_array($j, $reals)) {
$schema_insert .= str_replace(".",",", $row[$j]) . $sep;
} else {
$schema_insert .= $row[$j] . $sep;
}
}
else
$schema_insert .= "" . $sep;
}

$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}

最佳答案

这行得通吗?由于 sqlsrv_fetch_array 返回一个以字段名称作为键的关联数组,我们可以将其作为第一行输入。

$result=sqlsrv_query($conn,$sql) or die("Couldn't execute query:<br>" . sqlsrv_error(). "<br>" . sqlsrv_errno()); 

$file_ending = "csv";
$reals=array();
//header info for browser
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character

$firstRow = true;


//start while loop to get data
while($row = sqlsrv_fetch_array($result))
{
if($firstRow)
{
$names = array_keys($row);
$namesToPrint = '';

foreach($names as $idx => $name)
{
if($idx % 2 != 0)
{
$namesToPrint .= $name.',';
}
}

$namesToPrint = substr($namesToPrint, 0, -1);

print $namesToPrint."\n";

$firstRow = false;
}

$schema_insert = "";
for($j = 0; $j < sqlsrv_num_fields($result); $j++)
{
if ($row[$j] != "") {
if (in_array($j, $reals)) {
$schema_insert .= str_replace(".",",", $row[$j]) . $sep;
} else {
$schema_insert .= $row[$j] . $sep;
}
}
else
$schema_insert .= "" . $sep;
}

$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}

关于php - 获取csv文件中的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com