How to generate HTML output in PHP
P粉176203781
P粉176203781 2023-08-22 14:41:53
0
2
578
<p>I want to conditionally output HTML to generate a page, so what is the easiest way in PHP 4? Do I need to use a template framework like Smarty? </p> <pre class="brush:php;toolbar:false;">echo '<html>', "n"; // I believe there is a better way! echo '<head>', "n"; echo '</head>', "n"; echo '<body>', "n"; echo '</body>', "n"; echo '</html>', "n";</pre>
P粉176203781
P粉176203781

reply all(2)
P粉578343994

Try using it like this (heredoc syntax):

$variable = <<<XYZ
<html>
<body>

</body>
</html>
XYZ;
echo $variable;
P粉598140294

There are several ways to output HTML in PHP.

1. Between PHP tags

<?php if(condition){ ?>
     <!-- 这里是HTML -->
<?php } ?>

2. Use echo

if(condition){
     echo "这里是HTML";
}

When using echo, if you want to use double quotes in HTML, you must use single quotes for echo, like this:

echo '<input type="text">';

Or you can escape them like this:

echo "<input type=\"text\">";

3. Heredocs

4. Nowdocs (since PHP 5.3.0)

Template Engine is used for using PHP in documents that mainly contain HTML. In fact, PHP's original purpose was to be a template language. This is why in PHP you can use short tags such as <?=$someVariable?>) to output variables.

There are other template engines (such as Smarty, Twig, etc.) that make the syntax more concise (such as {{someVariable}}).

The main benefit of using a template engine is to separate design (Display logic) from coding (Business logic). It also makes the code cleaner and easier to maintain in the long term.

If you have more questions, please feel free to leave a message.

For more reading on these, see PHP Documentation.


Note: The use of PHP's short tags <? and ?> is not recommended because they are only enabled in the php.ini configuration file The short_open_tag directive is available, or PHP is configured with the --enable-short-tags option. Starting with PHP 5.4, they are available regardless of settings .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!