Embedding HTML in PHP: Common Methods and Code Examples
This article explains several common techniques for embedding HTML within PHP code, including echo statements, mixing PHP inside HTML files, using heredoc syntax, and including external HTML files via the include() function, each illustrated with clear code examples.
PHP provides multiple ways to embed HTML, and this guide lists several common methods.
Output HTML with echo
<code><?php
$int=rand(0,1);
if($int==1){
echo "<p>取到的随机数是1</p>";
}else{
echo "<p>取到的随机数不是1</p>";
}
?>
</code>Embed PHP inside HTML
This approach allows inserting PHP code at any point within a large block of HTML.
<code><!DOCTYPE html>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<meta http-equiv=\"Content-Language\" content=\"zh-CN\" />
<title>Hello World</title>
</head>
<body>
<?php
echo \"Hello world!这是正文\";
?>
</body>
</html>
</code>Use heredoc (<<<) syntax
The heredoc syntax is useful for outputting large blocks of HTML without escaping.
<code><?php
print <<<EOT
<div class=\"slidecont\">{$label[deepblue_mainslide]}</div>
<div class=\"newcontainter\">
<div class=\"head\">{$label[deepblue_mainh1]}</div>
<div class=\"cont\" id=\"Tab1\">{$label[deepblue_maint1]}</div>
<div class=\"cont\" id=\"Tab2\">{$label[deepblue_maint2]}</div>
</div>
<a href=\"{$rs[url]}\" title=\"{$rs[descrip]}\" target=\"_blank\">{$rs[name]}</a>
EOT;
?>
</code>Include external HTML file
An external HTML file (e.g., test.html) can be inserted using PHP's include() function.
<code><?php
include(\"test.html\");
?>
</code>php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.