Backend Development 3 min read

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中文网 Courses
php中文网 Courses
php中文网 Courses
Embedding HTML in PHP: Common Methods and Code Examples

PHP provides multiple ways to embed HTML, and this guide lists several common methods.

Output HTML with echo

<code>&lt;?php
    $int=rand(0,1);
    if($int==1){
        echo "&lt;p&gt;取到的随机数是1&lt;/p&gt;";
    }else{
        echo "&lt;p&gt;取到的随机数不是1&lt;/p&gt;";
    }
?&gt;
</code>

Embed PHP inside HTML

This approach allows inserting PHP code at any point within a large block of HTML.

<code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
      &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;
      &lt;meta http-equiv=\"Content-Language\" content=\"zh-CN\" /&gt;
      &lt;title&gt;Hello World&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;?php
      echo \"Hello world!这是正文\";
    ?&gt;
&lt;/body&gt;
&lt;/html&gt;
</code>

Use heredoc (<<<) syntax

The heredoc syntax is useful for outputting large blocks of HTML without escaping.

<code>&lt;?php
      print &lt;&lt;&lt;EOT
      &lt;div class=\"slidecont\"&gt;{$label[deepblue_mainslide]}&lt;/div&gt;
      &lt;div class=\"newcontainter\"&gt;
          &lt;div class=\"head\"&gt;{$label[deepblue_mainh1]}&lt;/div&gt;
          &lt;div class=\"cont\" id=\"Tab1\"&gt;{$label[deepblue_maint1]}&lt;/div&gt;
          &lt;div class=\"cont\" id=\"Tab2\"&gt;{$label[deepblue_maint2]}&lt;/div&gt;
      &lt;/div&gt;
      &lt;a href=\"{$rs[url]}\" title=\"{$rs[descrip]}\" target=\"_blank\"&gt;{$rs[name]}&lt;/a&gt;
EOT;
?&gt;
</code>

Include external HTML file

An external HTML file (e.g., test.html) can be inserted using PHP's include() function.

<code>&lt;?php
    include(\"test.html\");
?&gt;
</code>
embeddingphpHTMLincludeHeredoc
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.