无法将PHP变量传递给file_get_contents()
I am a newbie coder trying to build a simple web app using PHP. I am trying to send an HTML email that has a variable that will change each time it is sent. The code to initiate the email is 'email.php' and contains:
$body = file_get_contents('welcome/green2.html.php');
Within the 'green2.html.php' file, I have a variable called $highlight that needs to be populated. The $highlight variable is defined within the 'email.php' file. I had tried to simply add within the 'green2.html.php' file, however it is not being parsed. I get a blank space where the variable should be when it is output.
Also, I have done an include 'welcome/green2.html.php' within the 'email.php' file. When I echo it, the $highlight var is shown on the resulting page, but not if I echo $body.
Any help would be much appreciated!
我是一名新手编码器,试图使用PHP构建一个简单的Web应用程序。 我正在尝试发送一封HTML电子邮件,其中包含一个每次发送时都会更改的变量。 启动电子邮件的代码是'email.php'并包含: p>
$ body = file_get_contents('welcome / green2.html.php');
code > pre>
在'green2.html.php'文件中,我有一个名为$ highlight的变量,需要填充。 $ highlight变量在'email.php'文件中定义。 我曾试图在'green2.html.php'文件中添加,但它没有被解析。 我得到一个空格,输出时变量应该是空格。 p>
另外,我在'email.php'文件中添加了'welcome / green2.html.php'。 当我回显它时,$ highlight var显示在结果页面上,但如果我回显$ body则不会。 p>
非常感谢任何帮助! p>
div>
Have you tried the str_replace function? http://php.net/manual/en/function.str-replace.php.
Add a placeholder in HTML (for instance #name# for name, #email# for email), and then use the string replace function once you've loaded the content of the file.
$bodytag = str_replace("#name#", $name, $myfile);
Loading a file via file_get_contents()
will not cause it to be parsed by PHP. It will simply be loaded as a static file, regardless of whether it contains PHP code or not.
If you want it to be parsed by PHP, you would need to include
or require
it.
But it sounds like you're trying to write a templating system for your emails. If this is what you're doing, you'd be better off not having it as PHP code to be parsed, but rather having placeholder markers in it, and then using str_replace()
or similar functions to inject variables from your main program into the string.
Hope that helps.
Use http://php.net/manual/en/function.sprintf.php put a %s in your code instead of the variable read the content and put the string into the sprintf with the variable you want to put that's it. Hope this will help.