Adam Holmes Adam Holmes - 4 months ago 8
HTML Question

What is the best practice to use when using PHP and HTML?

I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using php and html. Is it better to have the whole document in php and echo html like so:

<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>


Or have a html file like so and just add in the php:

<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>


It seems tidier to echo html, especially if lots of php gets used throughout the page, but doing so loses all formatting of the html i.e. colors in the IDE etc.

Answer

There are varying opinions on this. I think there are two good ways:

  • Use a templating engine like Smarty that completely separates code and presentation.

  • Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:

    <?php $content = doSomething();
       // complex calculations
    ?>
    <html>
    <body>
      <?php echo $content; ?>       
      <div id="some_div">Content</div>
    </body>
    </html>
    

Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.