PHP - To echo or not to echo?

前端 未结 7 1030
[愿得一人]
[愿得一人] 2021-01-31 06:05

What is more efficient and/or what is better practice, to echo the HTML or have many open and close php tags?

Obviously for big areas of HTML it is sensible

相关标签:
7条回答
  • 2021-01-31 06:13

    I've made myself the same question long time ago and came up with the same answer, it's not a considerable difference. I deduct this answer with this test:

    <?
        header('content-type:text/plain');
        for ($i=0; $i<10; $i++) {
            $r = benchmark_functions(
                   array('output_embeed','output_single_quote','output_double_quote'),
                   10000);
            var_dump($r);
        }
    
        function output_embeed($i) {
            ?>test <?php echo $i; ?> :)<?
        }
    
        function output_single_quote($i) {
            echo 'test '.$i.' :)';
        }
    
        function output_double_quote($i) {
            echo "test $i :)";
        }
    
        function benchmark_functions($functions, $amount=1000) {
            if (!is_array($functions)||!$functions)
                return(false);
            $result = array();
            foreach ($functions as $function)
                if (!function_exists($function))
                    return(false);
            ob_start();
            foreach ($functions as $idx=>$function) {
                $start = microtime(true);
                for ($i=0;$i<$amount;$i++) {
                    $function($idx);
                }
                $time = microtime(true) - $start;
                $result[$idx.'_'.$function] = $time;
            }
            ob_end_clean();
            return($result);
        }
    ?>
    
    0 讨论(0)
  • 2021-01-31 06:20

    PHP solves this problem by what is known as heredocs. Check it out please.

    Example:

      echo <<<EOD
      <td class="itemname">{$k}s</td>
      <td class="price">{$v}/kg</td>
    EOD;
    

    Note: The heredoc identifer (EOD in this example) must not have any spaces or indentation.

    0 讨论(0)
  • 2021-01-31 06:20

    Personally I tend to prefer what looks the best as code readability is very important, particularly in a team environment. In terms of best practice I'm afraid I'm not certain however it is usually best practice to optimize last meaning that you should write it for readability first and then if you encounter speed issues do some refactoring.

    Any issues you have with efficiency are likely to be elsewhere in your code unless you are doing millions of echo's.

    Another thing to consider is the use of an MVC to separate your "views" from all of your business logic which is a very clean way to code. Using a template framework such as smarty can take this one step further leading to epic win.

    0 讨论(0)
  • 2021-01-31 06:22

    echo sends its argument further down the request processing chain, and eventually this string is sent to the client through a say, network socket. Depending on how the echo works in conjunction with underlying software layers (e.g. webserver), sometimes your script may be able to execute faster than it can push data to the client. Without output buffering, that is. With output buffering, you trade memory to gain speed - you echos are faster because they accumulate in a memory buffer. But only if there is no implicit buffering going on. One'll have to inspect Apache source code to see how does it treat PHPs stdout data.

    That said, anything below is true for output buffering enabled scripts only, since without it the more data you attempt to push at once the longer you have to wait (the client has to receive and acknowledge it, by ways of TCP!).

    It is more efficient to send a large string at once than do N echos concatenating output. By similar logic, it is more efficient for the interpreter to enter the PHP code block (PHP processing instruction in SGML/XML markup) once than enter and exit it many times.

    As for me, I assemble my markup not with echo, but using XML DOM API. This is also in accordance with the article linked above. (I reprint the link: http://hsivonen.iki.fi/producing-xml/) This also answers the question whether to use one or many PHP tags. Use one tag which is your entire script, let it assemble the resulting markup and send it to the client.

    0 讨论(0)
  • 2021-01-31 06:23

    Whatever you do, don't print XML!

    See HOWTO Avoid Being Called a Bozo When Producing XML

    0 讨论(0)
  • 2021-01-31 06:27

    From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person.

    The more a homogeneous block the markup is, the cleaner the work.

    One way to achieve this is to prepare as much as possible in variables, and using the heredoc syntax:

    // Preparation
    
    $var1 = get_value("yxyz");
    $var2 = get_url ("abc");
    $var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
    $var4 = htmlentities(get_value("def"));
    
    // Output  
    
    echo <<<EOT
    
     <fieldset title="$var4">
       <ul class="$var1">
         <li>
           $var2
         </li>
       </ul>
      </fieldset>
    
    EOT;
    

    You will want to use more sensible variable names, of course.

    Edit: The link pointed out by @stesch in the comments provides some good arguments towards using a serializer when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in every situation, especially from a maintenance standpoint where templates are so much more easy to edit, but the link is well worth a read. HOWTO Avoid Being Called a Bozo When Producing XML

    Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.

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