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

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

Embed PHP inside HTML

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

<!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>

Use heredoc (<<<) syntax

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

<?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;
?>

Include external HTML file

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

<?php
    include(\"test.html\");
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendEmbeddingPHPincludeHeredoc
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

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.