Reputation:
My index.php looks like this:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title?></title>
</head>
<body>
<p>Hi, this is my homepage. I'll include some text below.</p>
<?php
include "myfile.php";
?>
</body>
</html>
"myfile.php" e.g. includes the following:
<?php
$title = "Hi, I'm the title tag…";
?>
<p>Here's some content on the site I included!</p>
The <p>
gots outputted but the <title>
tag stays blank.
How can I reach to get $title
from the included site and also show the included content inside the <body>
tag?
Upvotes: 1
Views: 282
Reputation: 393
Here is my solution:
index.php
<?php
// Turn on the output buffering so that nothing is printed when we include myfile.php
ob_start();
// The output from this line now go to the buffer
include "myfile.php";
// Get the content in buffer and turn off the output buffering
$body_content = ob_get_contents();
ob_end_clean();
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title?></title>
</head>
<body>
<p>Hi, this is my homepage. I'll include some text below.</p>
<?php
echo $body_content; // Now, we have the output of myfile.php in a variable, what on earth will prevent us from echoing it?
?>
</body>
</html>
myfile.php
is unchanged.
P.S: As Noman suggested, you can first include 'myfile.php';
at the beginning of index.php
, then echo $content;
inside body tag, and change myfile.php
into something like this:
<?php
$title = "Hi, I'm the title tag"
ob_start();
?>
<p>Here's some content on the site I included!</p>
<?php
$content = ob_get_contents();
ob_end_clean();
?>
Upvotes: 1
Reputation: 1487
There is another way to do it:
index.php
<?php
include "myfile.php";
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title?></title>
</head>
<body>
<p><?php $content; ?></p>
</body>
</html>
myfile.php
<?php
$title = "Hi, I'm the title tag…";
$content = "Here's some content on the site I included!";
?>
Upvotes: 0