I found a lot of example how to create csv and send it as attachment. All of these examples upload the file on the server. Is there a way to send the csv created without upload it so to be sent directly as attachment?
CodePudding user response:
you can try to use addStringAttachment
CodePudding user response:
Of course there is! There are many ways of making CSV files, but a basic one is very simple:
$data = [
['id', 'name', 'colour'],
[1, 'Fred', 'blue'],
[2, 'Jane', 'orange'],
[3, 'Hassan', 'purple'],
];
$csv = fopen('file.csv', 'wb');
foreach($data as $line) {
fputcsv($csv, $line);
}
fclose($csv);
//then later on, to send it with PHPMailer
$mail->addAttachment('file.csv');
Of course the data can come from anywhere - a database, a calculation, a remote web service, or whatever.
You could use output buffering to capture the CSV string output by fputcsv
and pass that directly to addStringAttachment
, which would mean you don't even need to write the file to disk before sending.