views:

95

answers:

3

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

+3  A: 

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>';
} ?>
Max Shawabkeh
I need it to be included in the php coding though. In an if statement. I need it to be more like <?PHP if(var=true){<html> <title>YAY</title></html>}
Sean Booth
Using Max's example you can easily achieve what you are further asking for in your comment....
drlouie - louierd
@Sean Booth: The *alternative syntax for control statements* is much easier to read:http://www.php.net/manual/en/control-structures.alternative-syntax.php
Felix Kling
Mixing "normal" HTML output and echoing HTML makes it even harder to read the code. Your updated example is not very good.
Felix Kling
@Felix: There's a clear note about what you **should** do. The example simply shows what you **can** do.
Max Shawabkeh
@Felix: Thank you so much! That worked PERFECTLY, I figured there was a pretty simple way, I am still just learnign PHP (obviously)
Sean Booth
A: 

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 ?>
Felix Kling
A: 

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).

kemp