繁体   English   中英

包含之前包含的 PHP 回显变量

[英]PHP echo variable from include before include

我的 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>

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

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

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

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

这是我的解决方案:

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:正如诺曼所建议的,您可以先include 'myfile.php'; index.php的开头,然后echo $content; 在 body 标签内,并将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();
?>

还有另一种方法可以做到:

索引.php

<?php
include "myfile.php";
?>

<!DOCTYPE html>
<html>
<head>
<title><?php echo $title?></title>
</head>
<body>

<p><?php $content; ?></p>

</body>
</html>

我的文件

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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