来自include之前的PHP echo变量

时间:2016-09-19 07:26:20

标签: php html include title

我的index.php看起来像这样:

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

&#34; myfile.php&#34;例如包括以下内容:

<?php
$title = "Hi, I'm the title tag…";
?>
<p>Here's some content on the site I included!</p>

<p> gots已输出但<title>标记仍为空白。

如何从包含的网站获取$title并在<body>代码中显示所包含的内容?

2 个答案:

答案 0 :(得分:1)

这是我的解决方案:

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没有变化。

PS:正如Noman建议的那样,您可以先include 'myfile.php';开始index.php,然后在正文标记内echo $content;,然后将myfile.php更改为以下内容:< / p>

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

答案 1 :(得分:0)

还有另一种方法:

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