PHP file_get_contents 混合媒体 (html/images)

PHP file_get_contents with mixed media (html/images)

我正在处理一个包含 html 电子邮件模板的项目。如果您直接查看内容,则内容基本上可以在浏览器中看到,并且一切正常。它主要包含带有徽标的文本。

在我的 PHP 中,我试图获取此 HTML 模板的内容并将其作为我的 HTML 电子邮件发送。

除图像外一切正常:

<?php 

// vars
$subject = 'Test Email Subject';
$body = file_get_contents("communication.php");

// Email
$objEmail = new SendMail;
$objEmail
   -> setFrom('noreply@domain.com')
   -> setTo('user@domain.com')
   -> setSubject($subject)
   -> sendHTMLEmail($body);

?>

HTML 它本身只是一个基本的 div,带有包含图像完整路径的 img 标签。

我假设 file_get_contents 只是获取代码,不会下载任何东西。

有什么原因导致直接 link 图片不起作用,或者它们是否需要以某种方式编码到电子邮件中?

我想 communication.php 是你的模板,你使用 PHP 因为你里面有一些变量。

基本上您不应该对 .php 文件执行 file_get_contents,因为内容将是文件的源代码。

您有 3 个解决方案

1 / 第一个是用自定义变量构建一个 template.html(不管扩展名是什么)。您可以决定如何编写变量##firstname## {{lastname}} ...

虽然你有 body 你应用了一些替换

$tpl = file_get_contents("template.html");
$search = array('##lastname##');
$replace = array($lastname);
$body = str_replace($search, $replace, $tpl);

2/ 第二个最好。根据邮件你可以有插件。你可以看看 swiftmailer 及其装饰器插件 http://swiftmailer.org/docs/plugins.html#decorator-plugin

3/ 使用像 twig 这样的模板引擎,并使用 ob_start、ob_flush

在缓冲区中捕获输出