在 PHP 中回显 HTML 的最佳方式 [已关闭]

2022-08-30 23:59:24

我是一个相当有经验的PHP程序员,我只是想知道回显大量HTML代码的最佳方式是什么(最佳实践)。

这样做是否更好:

<?php
echo "<head>
<title>title</title>
<style></style>
</head>";
?>

或者这个:

<?php
define("rn","\r\n");
echo "<head>".rn
."<title>title</title>".rn
."<style></style".rn
."</head>".rn;
?>

我倾向于使用第二个,因为它不会弄乱php源代码中的缩进。这是大多数人的做法吗?


答案 1

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>

将名称和地址插入模板文件的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');

除了Smarty之外,还有数十种合理的模板框架选择,以满足您的口味。有些很简单,许多具有一些相当复杂的功能。


答案 2

您也可以将 HTML 放在 PHP 代码块之外:

<?php
    // PHP code
?>
<head>
<title>title</title>
<style></style>
</head>
<?php
    // further PHP code
?>

推荐