简体   繁体   中英

PHP echo variable from include before include

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" eg 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?

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.

PS: 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();
?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM