PHP MySQL查询特定字段为CSV

我正在尝试根据查询结果制作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);
评论
_RocY、
_RocY、

fputcsv is expecting an array for the second parameter, so you can either build the data before hand, or just add [] round the data in the call to pass it as an array...

fputcsv($output, [ $row['STUDENTID'], $name, ... ])
点赞
评论