过去几个小时我一直被难住了…
我想发送一个电子邮件与HTML头,PHP文件体,和HTML页脚。这封电子邮件将从PHP脚本发送。我有:
/************************ send_email.php *******************/
$first_name = John; //I want to use this variable in body.php
$to = "fake_email@example.com";
$subject = "This is a test email";
//create the header for the email
$header = 'header_email.html';
$fd = fopen($header,"r");
$message_header = fread($fd, filesize($header));
fclose($fd);
//create the body for the email
$body = 'body.php';
$fd = fopen($body,"r");
$message_body = fread($fd, filesize($body));
fclose($fd);
$footer = 'footer_email.php';
$fd = fopen($footer,"r");
$message_footer = fread($fd, filesize($footer));
fclose($fd);
//the final message consists of the header+body+footer
$message = $message_header.$message_body.$message_footer;
mail($to, $subject, $message); //send the email
/************************ end send_email.php *******************/
/************************ header_email.html *******************/
<html>
<body>
/************************ end header_email.html **************/
/************************ body.php *******************/
//some HTML code
<?php echo $first_name; ?>
//some more HTML code
/************************ end body.php **************/
/************************ footer_email.html *******************/
</body>
</html>
/************************ end footer_email.html *************/
这段代码的问题是,电子邮件没有在正文中发送变量$first_name。该变量为空。这就好像PHP代码没有执行,它被视为HTML文件。
有没有人可以帮助我解决在我包含并发送电子邮件的外部PHP文件的正文中使用变量的问题?
谢谢。
您正在读取文件的内容,然后将其插入正文。这意味着其中的任何PHP代码都不会被执行。
你要做的是使用include
和输出缓冲;比如:
ob_start(); // start output buffering
$body_file = 'body.php';
include $body;
$body_output = ob_get_contents(); // put contents in a variable
ob_end_clean();
输出缓冲所做的是"捕获"输出,否则只是打印到浏览器。然后你可以把它们放在一个变量中,就像我做的($body_output = ob_get_contents();
)或刷新它(实际发送到浏览器)。