2016-09-19 51 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