Reputation: 3432
I have an array with keys and values that I want to email as an attachment in csv form. What I am trying is this:
...
$mail->addStringAttachment(create_csv($dataCSV), "test.csv", $encoding = 'base64', $type = "text/csv", $disposition = 'attachment');
...
and below that, I declare my create_csv
function
function create_csv(array &$array) {
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
foreach ($array as $key => $value) {
fputcsv($df, $key);
fputcsv($df, $value);
}
fclose($df);
return ob_get_clean();
}
This though ends up attaching a file with no contents on my email, even though if I debug key
, value
at that point they have the expected values.
Why is this, and how can I fix it?
Upvotes: 2
Views: 74
Reputation: 37108
You misuse fputcsv. The function's second argument is a row in the CSV.
If you change your loop to
foreach ($array as $key => $value) {
fputcsv($df, [$key, $value]);
}
The attached csv will be a list of rows with 2 coma-separated values. e.g. for $dataCSV = ['one','two','three']
the attachment will be
0, one
1, two
2, three
Upvotes: 2