来自字符串的PHP附件 [英] Php attachment from string

查看:92
本文介绍了来自字符串的PHP附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成.pdf文件的脚本.该脚本以字符串形式返回此文件,然后我可以使用file_put_contents()将其保存

I have a script generating .pdf file. This script return this file as string and then I can save it with file_put_contents()

$output = $dompdf->output();
file_put_contents("myfile.pdf", $output);

我想使用PHPMailer将此文件作为附件添加到我的电子邮件中.如果我在磁盘上有一个文件,我只需为其写路径和新名称:

I want to add this file as attachment to my email using PHPMailer. If I have a file on disk I just write path to it and new name:

$mail->addAttachment('/path/to/file.pdf', 'newname.pdf'); 

但是我可以添加附件而不将myfile.pdf保存到磁盘吗?像这样的东西:

But can I add attachment without saving myfile.pdf to disk? Something like that:

$mail->addAttachment($output, 'myfile.pdf'); 

此字符串返回错误:

PHP Fatal error:  Call to a member function addAttachment() on a non-object

如何在不保存的情况下将字符串类型转换为文件类型?

How can I transform string type to file type without saving?

UPD: 完整代码

$output = $dompdf->output();
$name = 'title.pdf';
    $mail->isSMTP();                                      // Set mailer to use SMTP
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.***.org';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '***@***.orgg';                 // SMTP username
$mail->Password = '******************';                           // SMTP password
$mail->SMTPSecure = 'tls';

$mail->From = 'aaa@bbb.com';
$mail->FromName = 'John';
$mail->addAddress('peter@parker.com', 'Joe User');     // Add a recipient

$mail->addStringAttachment($output, $name);

                          // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

推荐答案

有一个 addStringAttachment() 方法似乎很适合您的需求:

There's an addStringAttachment() method that seems to fit your need:

addStringAttachment()

addStringAttachment(string $string, string $filename, string $encoding = self::ENCODING_BASE64, string $type = '', string $disposition = 'attachment') : boolean

添加字符串或二进制附件(非文件系统).

Add a string or binary attachment (non-filesystem).

此方法可用于附加ascii或二进制数据,例如数据库中的BLOB记录.

This method can be used to attach ascii or binary data, such as a BLOB record from a database.

这篇关于来自字符串的PHP附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆