使用file_get_contents()在html文件中设置php变量


Setting php variable in html file using file_get_contents()

我设置了一个自动电子邮件系统,可以将html文件作为电子邮件发送。我使用将该文件带到PHPMailer的电子邮件中

$mail->msgHTML(file_get_contents('mailContent.html'), dirname(__FILE__));

在PHP源代码中,在添加mailContent.html之前,我有一个变量$name='John Appleseed'(它是动态的,这只是一个示例)

在HTML文件中,我想知道是否有一种方法可以在<p>标记中使用这个$name变量。

您可以在mailContent.html文件中添加一个类似%name%的特殊字符串,然后您可以将该字符串替换为所需的值:

mailContent.html:中

Hello %name%,
…

在您的PHP代码中:

$name='John Appleseed';
$content = str_replace('%name%', $name, file_get_contents('mailContent.html'));

$content将具有值Hello %name%, …,您可以发送它:

$mail->msgHTML($content, dirname(__FILE__));

您还可以使用两个数组来替换一次调用str_replace()中的几个字符串:

$content = str_replace(
    array('%name%', '%foo%'),
    array($name,    $foo),
    file_get_contents('mailContent.html')
);

您还可以使用一个数组替换一次调用strtr()中的几个字符串:

$content = strtr(
    file_get_contents('mailContent.html'),
    array(
        '%name%' => $name,
        '%foo%' => $foo,
    )
);

您需要为此使用模板系统。模板化可以用PHP本身完成,方法是在.php文件中编写HTML,如下所示:

template.php:

<html>
<body>
    <p>
        Hi <?= $name ?>,
    </p>
    <p>
        This is an email message.  <?= $someVariable ?>
    </p>
</body>
</html>

使用<?= $variable ?><?php echo $variable ?>添加变量。如果变量来自用户输入,请确保使用htmlspecialchars()正确转义HTML。

然后对程序中的模板执行以下操作:

$name = 'John Appleseed';
$someVariable = 'Foo Bar';
ob_start();
include('template.php');
$message = ob_get_contents();
ob_end_clean();
$mail->msgHTML($message, dirname(__FILE__));

除了使用PHP进行简单的模板化之外,还可以使用Twig等PHP模板化语言。

这里有一个使用extractob_* 的函数

extract将键转换为数组中键值为的变量。希望这是有道理的。它将把数组键变成变量。

function getHTMLWithDynamicVars(array $arr, $file)
{
    ob_start();
    extract($arr);
    include($file);
    $realData = ob_get_contents();
    ob_end_clean();
    return $realData;
}

呼叫者示例:

$htmlFile = getHTMLWithDynamicVars(['name' => $name], 'mailContent.html');

在我的一个旧脚本中,我有一个函数,它可以解析文件中类似{{ variableName }}的变量,并从数组查找中替换它们。

function parseVars($emailFile, $vars) {
    $vSearch = preg_match_all('/{{.*?}}/', $emailFile, $vVariables);
    for ($i=0; $i < $vSearch; $i++) {
        $vVariables[0][$i] = str_replace(array('{{', '}}'), NULL, $vVariables[0][$i]);
    }
    if(count($vVariables[0]) == 0) {
        throw new TemplateException("There are no variables to replace.");
    }
    $formattedFile = '';
    foreach ($vVariables[0] as $value) {
        $formattedFile = str_replace('{{'.$value.'}}', $vars[$value], $formattedFile);
    }
    return $formattedFile;
}

发送邮件的同一文件中是否有$name变量?然后,您可以将其替换为占位符;

__NAME__放在要显示名称的HTML文件中,然后使用str_ireplace('__NAME__', $name, file_get_contents('mailContent.html'))将占位符替换为$name变量。