【问题标题】:How to access csv file after converting a json array to csv将json数组转换为csv后如何访问csv文件
【发布时间】:2019-12-01 02:45:46
【问题描述】:

我需要将一个 json 数组转换为 .csv 文件,所以我查找了它并设法想出了一些代码。现在,我应该有一个 csv 文件,但是我不知道如何将其作为附件发送到特定的电子邮件地址。

$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()

我的最终目标是将此 csv 文件作为附件发送到特定的电子邮件地址。任何帮助将不胜感激。

【问题讨论】:

  • 您尝试将文件作为电子邮件附件发送的任何代码?
  • 您的问题标题与您的要求不同。
  • 对于造成的误解,我深表歉意,我的意思是我需要访问该文件才能通过电子邮件发送它

标签: php json file csv pointers


【解决方案1】:

我已根据您的要求更新了以下示例

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");

【讨论】:

  • 感谢您的回答,这似乎对我有用,但是附加的 csv 文件是空白的。尽管如此,该数组还是充满了数据。知道为什么会这样吗?
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 2019-02-23
  • 1970-01-01
  • 2020-06-08
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多