tags:

views:

480

answers:

8

What is more efficient and/or what is better practice. To echo the html or the have many open and close php tags?

Obviously for big areas of html it is sensible to open and close the php tags. What about when dealing with something like generating XML... should you open and close the PHP tags with a single echo for each piece of data or use a single echo with the xml tags included in quotations?

+2  A: 

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.

Sarfraz
+1 for proper use of curly braces
Joe Philllips
@D03boy: Thanks buddy :)
Sarfraz
+3  A: 

Whichever makes sense to you. The performance difference is marginal, even if a large echo is faster.

But an echo of a big string is hard to read and more <?php echo $this->that; ?> tell a story :)

Horia Dragomir
+1 and besides, you will probably use some kind of cache if you have performance problems, which should eliminate the need for such distinction.
Itay Moav
+15  A: 

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.

Pekka
I didn't even know of the existence of heredoc - This is why I love stackoverflow... So much knowledge being shared. Thanks
Mark
Only bozos print XML. :-(
stesch
@stesch: true, a HTML example may have been more appropriate. On the other hand, I have no problems with generating small XML snippets that way. And why should I?
Pekka
@Pekka: http://hsivonen.iki.fi/producing-xml/
stesch
@stesch, all good points, especially the one about pretty printing. I still think that this way of producing XML is fine in many situations, and a serializer often overkill. Still, I'm adding a HTML example and adding a comment, including your link, to the XML one.
Pekka
WOW. This is some real awesome awesome stuff !
Skun
+1  A: 

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.

Jake Worrell
A: 

If you want better practice then you should be using a template engine. http://www.tinybutstrong.com/ or http://www.smarty.net/

Hasan Khan
+1  A: 

Whatever you do, don't print XML!

See HOWTO Avoid Being Called a Bozo When Producing XML

stesch
+1, funny to see two bozos have already been touched by the title. ;)
just somebody
+1  A: 

'echo' sends its argument further down the request processing chain, and eventually this string is sent to the client through a say, network socket. Since bandwidth is limited, sometimes your script will 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.

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!).

It is more efficient to send a large string at once then do N echoes concatenating output. With similiar 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/) That 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.

amn
+1  A: 

ive made my self the same question long time ago and came up with the same answer, its no a considerable diference. 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);
}
?>
useless