Caley Woods
Caley Woods

Reputation: 4737

PHP output CSV to email

I have a script that currently takes some data from a wordpress DB and then loops over the returned rows and uses fputcsv(). The file handle was setup with:

$fh = fopen('php://output', 'w');

The script is linked to a link of a webpage and when you click the link it downloads the CSV (using the content-disposition header).

Is it possible to write to php://output this CSV file and then use PHP's mail() function to send it in an attachment?

I have a mail function I've written that will set the MIME type to multipart/mixed, I'm just not sure how to create the actual attachment to be emailed.

Upvotes: 0

Views: 1155

Answers (1)

Marc B
Marc B

Reputation: 360602

Use tmpfile() instead. Write your CSV data to that temp file, then attach it to your email.

Plus, don't write your own mime handling/generating functions. Use a library like PHPMailer or Swiftmailer to do it for you. Far easier and far more reliable. Part of their attachment handling code allows you specify the filename the user sees, so even though it might be "/tmp/abc123def", it'll show up as "data.csv" (or whatever you specify) in the actual email.

Upvotes: 1

Related Questions