我应该将我的html直接放在php上还是从文件中读取[关闭]

I am very new to php and have a doubt regarding best practices. I want to know if, when returning html from php, I should include the html directly into the php file, inside an echo statement or load it from an external file. If I do load it from an external file, will there be a disk operation every time a user loads the page?

I don't know whether this is relevant, but the context is authentication. I want to send a Basic Authentication request to a php file, which will return a page.

You can mix PHP and HTML in same script page. While PHP intepreter find the code within PHP tag it will take that as PHP. Others will be displayed directly. See the following example.

<?php
$header = "PHP html Mix";
?>
<h1><?php echo $header; ?></h1>
<p>You can use php and html as mix. no need to echo static elements.</p>

Copy and past on a php file then run and see.

  • First we create php tag and assign a string to php variable.
  • Then we create just few html tags and text.
  • Between <h1> tag again a php tag introduced to echo the string.

If you want to put whole html inside if or for that also possible like follows.

<?php if($display==1){ ?>
<h2>Write whatever html within these start and close php tag.</h2>
<strong>no need to echo this in php</strong>
<?php } ?>

Having the server access multiple files upon a web request probably does increase disk activity but it needn't be a concern the overhead is small compared to db queries etc.

Take a look at wordpress... it probably works its way through 20 files or more before rendering any output.

I personally think it is good practice to keep your markup templates, even when interpolated with numerous <?=$var?> tags separate from your files which process logic and db queries

The best practice in using PHP with HTML is to combine PHP code inside <?php and ?> delimiters with pure (static) HTML. For instance, consider the example below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
    xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/1999/xhtml 
        http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Example</title>
</head>
<body>
  <p>The current date: <?php echo(date("Y-m-d")); ?>.</p>
</body>
</html>

So it's supposed to be used in that way whenever possible, preferably with an addition of an architectural design pattern like MVC (Model-View-Controller).