我是一个相当有经验的PHP编码器,我只是想知道回复大块HTML代码的最佳方法是什么(最佳实践).
这样做更好:
<?php
echo "<head>
<title>title</title>
<style></style>
</head>";
?>
Run Code Online (Sandbox Code Playgroud)
或这个:
<?php
define("rn","\r\n");
echo "<head>".rn
."<title>title</title>".rn
."<style></style".rn
."</head>".rn;
?>
Run Code Online (Sandbox Code Playgroud)
我倾向于使用第二个,因为它不会弄乱php源代码中的缩进.这是大多数人这样做的方式吗?
Dou*_* T. 20
IMO,最好的方法通常是将HTML单独存储在模板文件中.这是一个通常包含HTML的文件,其中包含一些需要填写的字段.然后,您可以根据需要使用一些模板框架安全地填写html文档中的字段.
Smarty是一个流行的框架,这是一个如何工作的例子(取自Smarty的速成课程).
模板文件
<html>
<head>
<title>User Info</title>
</head>
<body>
User Information:<p>
Name: {$name}<br>
Address: {$address}<br>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
将名称和地址插入模板文件的PHP代码:
include('Smarty.class.php');
// create object
$smarty = new Smarty;
// assign some content. This would typically come from
// a database or other source, but we'll use static
// values for the purpose of this example.
$smarty->assign('name', 'george smith');
$smarty->assign('address', '45th & Harris');
// display it
$smarty->display('index.tpl');
Run Code Online (Sandbox Code Playgroud)
除了Smarty之外,还有数十种合理的模板选择可供选择,以满足您的口味.有些很简单,很多都有一些相当复杂的功能.
Gum*_*mbo 14
您还可以将HTML放在PHP代码块之外:
<?php
// PHP code
?>
<head>
<title>title</title>
<style></style>
</head>
<?php
// further PHP code
?>
Run Code Online (Sandbox Code Playgroud)
mr-*_*-sk 10
别忘了你也可以访问HEREDOC(http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)
echo <<< HERE
<head>
<title>title</title>
<style></style>
</head>
HERE;
Run Code Online (Sandbox Code Playgroud)
此外,我会研究类似Smarty模板的东西 - 更重要的是MVC设计模式,它强制从业务逻辑中分离标记.