Attach CSV created with fputcsv to email
I have a function that compiles a custom CSV file using fputcsv. I also
have it email to an address submitted through a prior form via POST. I'm
sending headers so that way when the function is called, it just downloads
the CSV, but I'm unsure how to have it email AND attach the CSV, then
download the CSV.
Here is the entire function -
//SEND EMAIL
$emailTo = $_POST['$submitemail'];
$mailHeader = "From: **********r\n";
$mailHeader .= "Reply-To: ***********\r\n";
$mailHeader .= "MIME-Version: 1.0" . "\r\n";
$mailHeader .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$message = "Here is an email.... attach CSV too!";
$subject = "Email with text and CSV";
mail($emailTo, $subject, $message, $mailHeader);
//GATHER DATA
$user_ID = $id;
$query = "SELECT * FROM hours WHERE user_ID = '$user_ID' ORDER BY date ASC";
$query2 = "SELECT * FROM users WHERE ID = '$user_ID'";
$result = $db->query($query);
$result2 = $db->query($query2);
$row2 = $result2->fetch_object();
$full_name = $row2->full_name;
$organization = $row2->organization;
$importantstuff = array('Hours for - ' . $full_name, 'Site - ' .
$organization);
if (!$result) die('Couldn\'t fetch records');
$headers = $result->fetch_fields();
foreach($headers as $header) {
$head[] = ucfirst($header->name);
}
//START GENERATING CSV
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="report-'.
$full_name .'.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, array_values($importantstuff));
fputcsv($fp, array_values($head));
while ($row = $result->fetch_array(MYSQLI_NUM)) {
$row[1] = $full_name;
fputcsv($fp, array_values($row));
}
die;
}
So, this is where I get a little lost because I am sending the headers
before I actually have the entire CSV created, hence I can't attach them
to an email before everything is done. I'm not sure how I would accomplish
both in the same function. Can I?
No comments:
Post a Comment