Home  >  Q&A  >  body text

How to generate HTML output in PHP

<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粉176203781P粉176203781396 days ago571

reply all(2)I'll reply

  • P粉578343994

    P粉5783439942023-08-23 12:08:43

    Try using it like this (heredoc syntax):

    $variable = <<<XYZ
    <html>
    <body>
    
    </body>
    </html>
    XYZ;
    echo $variable;

    reply
    0
  • P粉598140294

    P粉5981402942023-08-23 10:12:12

    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 .

    reply
    0
  • Cancelreply