简体   繁体   中英

PHP MySQL query specific fields to CSV

I'm trying to make a CSV file out of my query result but I need to format the data first before writing it to the CSV.

I have a working code which prints the whole row to csv and is working fine.

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);

I understand that the code above ouputs the complete row. But is there way to format specific fields first before writing to 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);

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, ... ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM