How to generate HTML output in PHP
P粉176203781
2023-08-22 14:41:53
<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>
Try using it like this (heredoc syntax):
There are several ways to output HTML in PHP.
1. Between PHP tags
2. Use echo
When using echo, if you want to use double quotes in HTML, you must use single quotes for echo, like this:
Or you can escape them like this:
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 Theshort_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 .