2016-09-19 54 views
1

我的index.php看起来是这样的: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> 

“myfile.php” 例如包括以下内容:

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

输出的<p> GOTS但<title>标签保持空白。

如何从包含的网站获得$title并在<body>标签中显示包含的内容?

+0

你使用echo $标题屏幕显示。 –

+1

你想做什么。 'include'用于包含文件。让你的问题更清楚一点。 – Sasikumar

+0

在使用'$ title'变量之前,您的文件必须包含在内。 – Sasikumar

回答

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保持不变。

P.S:由于诺曼建议,可以先include 'myfile.php';index.php的开头,然后身体标记内echo $content;,并改变myfile.php弄成这个样子:

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

您自己的解决方案有效。但是,它是如何工作的。你能向我解释一下吗? – David

+1

当你包含'myfile.php'时,输出html部分。我使用ob_ *函数将其捕获到变量中,而不是将其打印出来,就这些了。为了获得存储在缓冲区中的字符串ob_get_contents()来清除输出缓冲区,然后关闭输出缓冲区,使用'ob_start()'打开输出缓冲区,'ob_get_contents() –

+0

感谢您的解释。祝你今天愉快! – David

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

中保存全局变量和重要变量没有帮助。这项工作应该如何? – David

+0

检查我更新的答案。 – Noman

+0

不太明白你的意思。你能把它嵌入我的代码中吗? – David