生成csv并发送到电子邮件

时间:2015-07-14 11:56:07

标签: php csv export-to-csv php-5.3

我想生成一个csv文件并将其发送到电子邮件,我试过这样:

function create_csv_string($data) {
// Open temp file pointer
if (!$fp = fopen('php://temp', 'w+')) return FALSE;
fputcsv($fp, array('Jour', 'Nombre 1', 'Nombre 2', 'Total'));
// Loop data and write to file pointer
foreach ($data as $line){
    fputcsv($fp, $line);
}
// Place stream pointer at beginning
rewind($fp);
// Return the data
return stream_get_contents($fp);

}
function send_csv_mail($csvData, $body, $to = 'myemail@gmail.com', $subject = 'Stats', $from = 'noreply@my.com') {
// This will provide plenty adequate entropy
$multipartSep = '-----'.md5(time()).'-----';
$headers = array(
    "From: $from",
    "Reply-To: $from",
    "Content-Type: multipart/mixed; boundary=\"$multipartSep\""
);
// Make the attachment
$attachment = chunk_split(base64_encode(create_csv_string($csvData)));
// Make the body of the message
$body = "--$multipartSep\r\n"
    . "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\r\n"
    . "Content-Transfer-Encoding: 7bit\r\n"
    . "\r\n"
    . "$body\r\n"
    . "--$multipartSep\r\n"
    . "Content-Type: text/csv\r\n"
    . "Content-Transfer-Encoding: base64\r\n"
    . "Content-Disposition: attachment; filename=\"Stats-Report-" . date("F-j-Y") . ".csv\"\r\n"
    . "\r\n"
    . "$attachment\r\n"
    . "--$multipartSep--";
// Send the email, return the result
return @mail($to, $subject, $body, implode("\r\n", $headers));
}

我的数组$csvData是这样的:

(
[2015-07-07] => 20
[2015-07-08] => 48
[2015-07-09] => 42
[2015-07-10] => 94
[2015-07-11] => 0
[2015-07-12] => 0
[2015-07-13] => 6
[2015-07-14] => 0
)

我收到了.csv的电子邮件,但此csv为空,此列array('Jour', 'Nombre 1', 'Nombre 2', 'Total')在一列中写道。你能帮我吗 ?提前谢谢。

0 个答案:

没有答案