【问题标题】:Why is my CSV file empty为什么我的 CSV 文件是空的
【发布时间】:2017-03-05 23:20:44
【问题描述】:

所以我有这个 php 脚本,在用户将数据输入表单后,数据被收集,一些数据被放入 .csv 文件,然后作为附件发送给用户,但我可以让电子邮件发送带有附件,但 .csv 文件始终为空,我不知道为什么这是我的代码

function send_csv_mail($csvData, $body, $to, $subject, $from)
{
    $multipartSep = '-----' . md5(time()) . '-----';

    $headers = [
        "From: $from",
        "Reply-To: $from",
        "Content-Type: multipart/mixed; boundary=\"$multipartSep\"",
    ];

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

    fputcsv($fp, ["Supplier Number", "Supplier Name", "Product Code", "Product Description", "Unit of Measure", "Product Group", "Buy Price EX GST"]);

    $testData = [
        ['123', '456', '789', '012', '345', '678', '901'],
        ['abc', 'def', 'ghi', '123', '456', '789', '012'],
        ['jkl', 'mno', 'pqr', '123', '456', '789', '012'],
    ];

    foreach ($testData as $data) {

        fputcsv($fp, $data);
    }

    fclose($fp);

    $attachment = chunk_split(base64_encode(file_get_contents($fp)));

    $newBody = "--$multipartSep\r\n"
        . "Content-Type: text/html; charset=ISO-8859" . "\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=\"New_Parts_and_Barcodes_Request.csv\"" . "\r\n"
        . "\r\n"
        . "$attachment" . "\r\n"
        . "--$multipartSep--";

    return @mail($to, $subject, $newBody, implode("\r\n", $headers));
}

很抱歉我的第一篇文章格式错误:)

【问题讨论】:

    标签: php forms csv email-attachments


    【解决方案1】:

    file_get_contents 需要文件路径作为参数,而不是文件指针。 试着改成

    $attachment = chunk_split(base64_encode(file_get_contents("php://temp")));

    【讨论】:

    • 好的,我已经按照您的建议进行了更改,但仍然无法通过数据,还有其他想法
    • 您可以尝试将fclose($fp); 移动到脚本末尾吗?
    • fclose($fp) 已移至脚本末尾的 return 之前。我又试了一次,还是没有骰子。