Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...