Generate CSV file and send as Email attachment PHP

Date Posted: February 26, 2015, 5:06 am


generate-csv-then-send-to-email

Recently I was tasked to create a module that will automatically generate a CSV report then send it to the admin email every month. The following code worked for me, which is included in a separate PHP file. To achieve a monthly notification email, you can use www.setcronjob.com which is basically a time-based scheduler that can be configured to visit your PHP link anytime depending on the schedule you set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function create_csv_string($data) {
   
    mysql_connect(HOST, USERNAME, PASSWORD);
    mysql_select_db(DATABASE);
   
    $data = mysql_query('SELECT id, company, name, company_account_number, email, phone_number, invoice FROM carlofontanos_table');

    // Open temp file pointer
    if (!$fp = fopen('php://temp', 'w+')) return FALSE;
   
    fputcsv($fp, array('ID', 'Company', 'Name', 'Company Account Number', 'Email', 'Phone Number', 'Invoice'));
   
    // Loop data and write to file pointer
    while ($line = mysql_fetch_assoc($data)) 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 = 'email@example.com', $subject = 'Website Report', $from = 'noreply@carlofontanos.com') {

    // This will provide plenty adequate entropy
    $multipartSep = '-----'.md5(time()).'-----';

    // Arrays are much more readable
    $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="Website-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));

}

$array = array(array(1,2,3,4,5,6,7), array(1,2,3,4,5,6,7), array(1,2,3,4,5,6,7));

send_csv_mail($array, "Website Report \r\n \r\n www.carlofontanos.com");

If you just want to generate a CSV File and make it available for download as soon as you access the page, then you can use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

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

fputcsv($output, array('ID', 'Company', 'Name', 'Company Account Number', 'Email', 'Phone Number', 'Invoice'));

mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DATABASE);

$rows = mysql_query('SELECT id, company, name, company_account_number, email, phone_number, invoice FROM transaxle_rewards_data');

while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me