1

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

1 Answer 1

4

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, ... ])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.