我知道这是一篇旧文章,但我真的很讨厌这里只有一个答案,建议不要混合使用html和php。与其混合内容,不如使用模板系统,或者自己创建一个基本的模板系统。
在PHP中
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
在html(/path/to/file.html)中
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
输出为:
Alice ate apples for lunch with Bob.