• September 1, 2017
    https://stackoverflow.com/questions/1100354/how-can-i-echo-html-in-php

    ปกติใช้แบบนี้

    echo '<html>', "\n"; // I'm sure there's a better way!
    echo '<head>', "\n";
    echo '</head>', "\n";
    echo '<body>', "\n";
    echo '</body>', "\n";
    echo '</html>', "\n";

    วิธีที่ง่ายกว่า คือ

    There are a few ways to echo HTML in PHP.

    1. In between PHP tags

    <?php if(condition){ ?>
         <!-- HTML here -->
    <?php } ?>

    2. In an echo

    if(condition){
         echo "HTML here";
    }

    With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:

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

    Or you can escape them like so:

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

    3. Heredocs

    4. Nowdocs (as of PHP 5.3.0)

    Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP’s original purpose was to be a templating language. That’s why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).

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

    The primary benefit of using a template engine is keeping the design (Presentation Logic) separate from the coding (Business Logic). It also makes the code cleaner and easier to maintain in the long run.

    If you have any more questions feel free to leave a comment. Further reading is available on these things in the PHP Documentation.

    หรือ

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

    หรือ

    <?php if ($something): ?>
        <some /> <tags /> <etc />
        <?=$shortButControversialWayOfPrintingAVariable ?>
        <?php /* A comment not visible in the HTML but is a bit of a pain to write */ ?>
    <?php else: ?>
        <!-- else -->
    <?php endif; ?>

    หรือ

    <?php
        /* do your processing here */
    ?>
    
    <html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?php foreach ( $something as $item ) : ?>
            <p><?=$item?></p>
        <?php endforeach; ?>
    </body>
    </html>

    or

    <html>
        <head>
    <%    if (X)
          {
    %>      <title>Definitely X</title>
    <%    }
          else
          {
    %>      <title>Totally not X</title>
    <%    }
    %>  </head>
      </html>

    or

    $page = 'hello world';
    $content = file_get_contents('html/welcome.html');
    $pagecontent = str_replace('[[content]]',$content,$page);
    echo($pagecontent);

    or

    <?php
    ob_start();
    echo('hello world');
    $php_output = ob_get_contents();
    ob_end_clean();
    ?>
    <h1> My Template page says </h1>
    <?php
    echo($php_output );
    ?>
    <hr>
    template footer


เวอไนน์ไอคอร์ส

ประหยัดเวลากว่า 100 เท่า!






เวอไนน์เว็บไซต์⚡️
สร้างเว็บไซต์ ดูแลเว็บไซต์

Categories