-1

I needed to convert a json array to .csv file, so I looked it up and managed to come up with some code. Now, I supposedly have a csv file, however I don't know how to send it as an attachment to a particular email address.

$arrayData = json_decode($jsonData, true);
$csvFileName = 'reports.csv';
$fp = fopen($csvFileName, 'w');

foreach($arrayData as $row){
    fputcsv($fp, $row);
}

fclose($fp);

$to = 'petkoutekal@gmail.com';                                             
$subject = 'IronWifi reports';
$message = 'reports';
$file = $fp;           //probably wrong

mailto()

My final goal is to send this csv file as an attachment to a particular email address. Any help will me appreciated.

Peter Utekal
  • 87
  • 10

1 Answers1

0

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");
  • Thank you for the answer, this seems like it is working for me, however the attached csv file is blank. Despite of that the array is full of data. Any idea why is this happening? – Peter Utekal Jul 23 '19 at 14:35