Sean Booth
Sean Booth

Reputation: 59

How do I insert an HTML page using PHP?

I wanted to know, is there any way to insert an HTML page into PHP without using the include function? I do not want to use an external html file, I want to write the html coding directly into the php coding.

Thanks for your help!

Upvotes: 0

Views: 1099

Answers (3)

Felix Kling
Felix Kling

Reputation: 817128

It is very bad habit to mix HTML and PHP (for more than just output control), but here you go:

$html = "<div>This is HTML</div>"
echo $html;

or Heredoc syntax:

$html = <<<EOF
<div>
    <p>
        Some longer HTML
    </p>
</div>
EOF;
echo $html;

or using alternative syntax for control statements if the output depends on some condition (or if you loop through an array etc.)(which is far better than building HTML with strings):

<?php if($foo): ?>

    <div> Some HTML output </div>

<?php else: ?>

    <div> Some other HTML </div>

<?php endif; ?>

or just

<?php //PHP here ?>

<div>HTML</div>

<?php //more PHP ?>

<div>more HTML</div>

<?php //even more PHP ?>

Upvotes: 0

Matteo Riva
Matteo Riva

Reputation: 25060

If you need to include snippets of HTML based on conditions, you can interleave code like this. In this case it's convenient to use the alternative syntax for loop controls

<?php if ( $var ): ?>
<html>
<title>YAY</title> 
</html>
<?php endif; ?>

so the code is clearer to read and you retain HTML syntax coloring (if your editor supports it).

Upvotes: 0

Max Shawabkeh
Max Shawabkeh

Reputation: 38663

Interleave it:

<?php

// Some php code.

?>

<html>
  <head>
    <title>Hello!</title>
  </head>
  <body>
    <h1>Header</h1>
    <?php /* More php code. */ ?>
    <p>Blah!</a>
  </body>
</html>
<?php /* Even more php. */ ?>

From a best practices point of view, though, avoid doing this - having business logic (PHP) and presentation (HTML) in the same place makes maintaining harder.

EDIT: To address your comment. You can either do it the same way, or use echo:

<?php if (x == 5) { ?>
  <p>Blah!</a>
<?php } else {
  echo '<p>Bleh</p>';
} ?>

Upvotes: 2

Related Questions