【问题标题】:how to load phtml file with variables assigned in a php file如何使用在 php 文件中分配的变量加载 phtml 文件
【发布时间】:2016-02-09 11:19:23
【问题描述】:

我正在尝试从 php 文件中的 phtml 加载或获取所有内容

一切正常,除了 phtml 文件中的变量没有加载值

这是我的 php 文件

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$code = rand(11111,99999);
$emailSubject = 'Email Verification';
$userEmail = 'some@some.com';

function loadEmailTemplate($pagelink='') {

$page = 'email-templates/' . $pagelink . '.phtml';
$pageContent = '';

ob_start();
include($page);
$pageContent = ob_get_contents();
ob_end_clean();

return $pageContent;
}

$mailBody = loadEmailTemplate('emailtemplate');

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: no-reply-some@some.com\r\n"."X-Mailer: php";
mail($userEmail, $emailSubject, $mailBody, $headers);
?>

我的 emailtemplate.phtml 是

<html>
<body>
<div style="background-color: #bb4e4e; width:80%; color: #fff;">
 Thank you for registering <?php echo $firstname; ?>, your verification code is <?php echo $code; ?>.
</div>
</body>
</html>

我在电子邮件中的输出或者如果我回显 $mailBody 是

 Thank you for registering <?php echo $firstname; ?>, your verification code is <?php echo $code; ?>.

但我的输出应该是

Thank you for registering John, your verification code is 52256.

这意味着 phtml 文件加载正常,但我想加载 php 文件中定义的变量值,我以为我们在定义 php 变量后加载 phtml 文件的内容,这将自动分配变量值,但事实并非如此,我我错了。有人可以帮我找到解决办法吗?

谢谢

【问题讨论】:

    标签: html php email-templates


    【解决方案1】:

    您需要告诉 Apache 处理这些文件,例如 php

    添加:

    <FilesMatch "\.ph(p[2-6]?|tml)$">
       SetHandler application/x-httpd-php
    </FilesMatch>
    

    到您的 apache 配置或 .htaccess 文件

    更多信息请阅读:https://php.net/manual/ro/install.unix.apache2.php

    【讨论】:

    • 仍然没有加载值
    • 如果你没有使用require_once(或类似的),它们还没有定义(不同的HTTP请求,不同的上下文)。尝试将它们传递给会话:$_SESSION['firstname'] = $firstname 在您的第一个文件中,并在 phtml 中回显
    • 为了使用会话变量,您还需要在 phtml 中启动会话:if(!session_id()) session_start();
    • 您对会话的想法很有效,谢谢。虽然我没有在 htaccess 中添加该代码,但 phtml 正在工作
    【解决方案2】:

    要解决您的问题,您只需在 phtml 文件中添加全局定义即可。

    你的 phtml 应该是这样的

    <?php global $firstname, $lastname; ?>
    <html>
    <body>
    <div style="background-color: #bb4e4e; width:80%; color: #fff;">
     Thank you for registering <?php echo $firstname; ?>, your verification code is <?php echo $code; ?>.
    </div>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-05
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多