Outputting HTML in PHP - the HTML is not being output where it is supposed to
I have this kind of HTML structure (stripped down for easy readability):
<head>
<title>My website!</title>
<?php include "myFile.php"; ?>
</head>
...
<div id="header"></div>
<div id="content">
<?php GetSomeStuff(); ?>
</div>
<div id="footer"></div>
And then I have the myFile.php:
<?php
ob_start();
function GetSomeStuff()
{
if(something)
{
ob_end_clean();
?>
<p>some html here!</p>开发者_如何学Go;
<?php
ob_start();
}
}
ob_end_clean();
?>
We expect that our HTML will now look like:
<div id="header"></div>
<div id="content">
<p>some html here!</p>
</div>
<div id="footer"></div>
Well, guess what. This is what it looks like:
<p>some html here!</p>
<div id="footer"></div>
Not only does it insert the p tag at the beginning of the body tag, but it also removes my beautiful header and content divs! Also, my header tag is empty - no title! :(
Obviously I am doing something wrong. How can I do this correctly? Please note that the output is gonna be a tad bigger than what I posted here. ;)
Your myFile.php should be as follows:
<?php
ob_start();
function GetSomeStuff()
{
if(something)
{
?>
<p>some html here!</p>
<?php
}
}
ob_end_clean();
?>
Try this:
<?php
ob_start();
function GetSomeStuff()
{
if(something)
{
ob_end_clean();
echo "<p>some html here!</p>";
ob_start();
}
}
ob_end_clean();
?>
Try ECHOing the HTML in you PHP-file. Apart from that probably causing the behaviour you're seeing, it's pretty bad style switching between PHP and HTML in a PHP-file - especially when separating PHP from HTML is something that you're trying to do.
Did you think about using a template engine like Smarty?
http://www.smarty.net/
I am doing that because I will be outputting a lot of HTML, and I do not want to do \n for a newline, to make sure the HTML looks proper.
Try this:
echo "<p>
some text
</p>";
And you will have "proper HTML" without using "\n".
精彩评论