我正在尝试从我的查询结果中创建一个 CSV 文件,但我需要先格式化数据,然后再将其写入 CSV。
我有一个工作代码,可以将整行打印到 csv 并且工作正常。
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('ID', 'Name', 'Country', 'Province/City' 'Address', 'Gender', 'Track', 'Payment Option'));,
$sql = "SELECT * FROM STUDENTINFO order by GRADELEVEL";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
fputcsv($output, $row);
}
fclose($output);
我知道上面的代码会输出完整的行。但是有没有办法在写入 csv 之前先格式化特定字段?
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$name = $row['FIRSTNAME']." ".$row['MIDDLENAME']." ".$row['LASTNAME'];
$gradelevel = glvlDESCRIPTION(row['GRADELEVEL']);
if ($row['TRACK'] == "AW")
{
$track = "A With Activities";
}
else
{
$track = "A Without Activities";
}
fputcsv($output, $row['STUDENTID'], $name, $row['COUNTRY'], $row['PROVINCE'], $row['ADDRESS'], $track...);
}
fclose($output);
摇曳的蔷薇