I have updated following example as per your requirement
function create_csvfileFromString($data) { // Function for convert string to csv file
// Open temp file pointer
if (!$fp = fopen('php://temp', 'w+')) return FALSE;
// 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_mailWithCSV ($csvData, $body, $to = 'ToEmailAddress@example.com', $subject = 'Email with attachment', $from = 'FromEmail@example.com') {
$multipartSep = '-----'.md5(time()).'-----';
// Arrays are much more readable
$headers = array(
"From: $from",
"Reply-To: $from",
"Content-Type: multipart/mixed; boundary=\"$multipartSep\""
);
// Add JSON file as attachment Make the attachment
$attachment = chunk_split(base64_encode(create_csvfileFromString($csvData)));
// Make the body of the MAIL 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=\"file.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("data1","data2","data3","data4"), array("array1","array2","array3","array4"), array("array6","array7","array8","array9"));
send_mailWithCSV($array, "Hello User!!! \n Email Message");