What is the best way to insert HTML via PHP?

前端 未结 11 2095
南方客
南方客 2020-12-12 15:26

Talking from a \'best practice\' point of view, what do you think is the best way to insert HTML using PHP. For the moment I use one of the following methods (mostly the lat

相关标签:
11条回答
  • 2020-12-12 16:04

    -1 for the typical hysterical ‘use [my favourite templating system] instead!’ posts. Every PHP post, even if the native PHP answer is a one-liner, always degenerates into this, just as every one-liner JavaScript question ends up full of ‘use [my favourite framework] instead!’. It's embarrassing.

    Seriously, we know about separating business logic and presentation concerns. You can do that — or not do that — in any templating system, whether PHP, Smarty or something completely different. No templating system magically separates your concerns without a bunch of thinking.

    (In fact a templating system that is too restrictive can end up with you having to write auxiliary code that is purely presentational, cluttering up your business logic with presentational concerns. This is not a win!)

    To answer the question that was asked, the first example is OK, but very difficult to read due to the bad indentation. See monzee's example for a more readable way; you can use the : notation or {}s, whichever you prefer, but the important thing for readability is to keep your HTML and PHP as a single, ‘well-formed’ indented hierarchy.

    And a final plea: remember htmlspecialchars(). Every time plain text needs to go in to a web page, this must be used, or it's XSS all over the floor. I know this question isn't directly related to that, but every time we post example code including < ?php echo($title) ?> or a framework equivalent without the escaping, we're encouraging the continuation of the security disaster area that most PHP apps have become.

    0 讨论(0)
  • 2020-12-12 16:05

    The most important consideration is keeping the logic separate from the presentation - less coupling will make future changes to both much more straightforward.

    You might even want to consider using some sort of templating system like smarty.

    0 讨论(0)
  • 2020-12-12 16:08

    If a template engine seems to much of a hassle you can make your own poor man's template engine. This example should definately be improved and is not suitable for all tasks, but for smaller sites might be suitable. Just to get you an idea:

    template.inc:

    <html><head><title>%title%</title></head><body>
    %mainbody%
    Bla bla bla <a href="%linkurl%">%linkname%</a>.
    </body></html>
    

    index.php:

    <?php
    $title = getTitle();
    $mainbody = getMainBody();
    $linkurl = getLinkUrl();
    $linkname = getLinkName();
    $search = array("/%title%/", "/%mainbody%/", "/%linkurl%/", "/%linkname%/");
    $replace = array($title, $mainbody, $linkurl, $linkname);
    $template = file_get_contents("template.inc");
    print preg_replace($search, $replace, $template);
    ?>
    
    0 讨论(0)
  • 2020-12-12 16:10

    It is better to completely seperate your logic (PHP code) from the presentation (HTML), by using a template engine.

    It is fast and easy to insert PHP into HTML, but it gets messy very fast, and is very difficult to maintain. It is a very quick and very dirty approach...

    As for which of all the template engines available in PHP is better, see these questions for example:

    • PHP templates - with PHP
    • Safe PHP Template Engines
    0 讨论(0)
  • 2020-12-12 16:12

    Something I wish I'd known when I first started doing PHP: Keep your heavy-lifting program code as far away from your HTML output as possible. That way they both stay in large, fairly contiguous, readable chunks.

    The best way I've found of doing this is to make a static HTML file first, maybe with some fake data so I can poke around and get the design right, then write PHP code to get the dynamic part of the output and glue them both together (how you do that part is up to you - you could do it with Smarty like others are suggesting).

    0 讨论(0)
  • 2020-12-12 16:14

    Smarty is ok, if you're not using a framework or when you're using a framework which doesn't have it's own templating system.

    Otherwise most PHP frameworks and younger generation CMS have their own templating system.

    In general the idea of a templating system is to have files which contain almost only HTML (View/Template File) and files which contain only data or business logics (Model or Controller Files).

    A Template File can look something like this (example from SilverStripe):

    <?xml version="1.0" encoding="UTF-8"?>
     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
        <head>
            <% base_tag %>
            $MetaTags
            <link rel="stylesheet" type="text/css" href="tutorial/css/layout.css" />
        </head>
        <body>
            <div id="Main">
                <ul id="Menu1">
                    <% control Menu(1) %>
                    <li class="$LinkingMode">
                        <a href="$Link" title="Go to the &quot;{$Title}&quot; page">$MenuTitle</a>
                    </li>
                    <% end_control %>
                </ul>
                <div id="Header">
                    <h1>$Title</h1>
                </div>
                <div id="ContentContainer">
                    $Layout
                </div>
                <div id="Footer">
                    <span>Some Text</span>
                </div>
            </div>
         </body>
    </html>
    

    You can see that there are only a few non-HTML code pieces inserted in the places where data will be inserted before the page is sent to the client.

    Your code can then (simplified) rather look something like:

    <?php
      unset($out);
      if($a) $out = '[SOME CONTENT TO INSERT INTO THE TEMPLATE]';
      else $out = '[SOME ALTERNATIVE CONTENT]';
      templateInsert($out);
    ?>
    

    The great thing about it: Your HTML can be seen as such and changed as such, your designer can make sense of it and doesn't have to look through your code trying to get the bits and pieces together from different places without any chance to view what she's doing. You on the other hand can make changes in the logic without worries about how it will look on the page. You'll most probably also make less mistakes because your code will be compact and therfore readable.

    0 讨论(0)
提交回复
热议问题