【问题标题】:PHP echo variable from include before include包含之前包含的 PHP 回显变量
【发布时间】:2016-09-19 07:26:20
【问题描述】:

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

&lt;p&gt; 已输出,但 &lt;title&gt; 标记保持空白。

我如何才能从包含的站点获取$title,并在&lt;body&gt; 标记内显示包含的内容?

【问题讨论】:

  • 你使用 echo $title 在屏幕上显示。
  • 你想做什么。 include 用于包含文件。让你的问题更清楚一点。
  • 在使用$title 变量之前必须包含您的文件。
  • @Sasikumar,更新了我的问题。是的,但我需要将它包含在 &lt;body&gt; 标签中,而不是在 title 标签之前。该怎么做?
  • 你可能可以......有点......通过对输出缓冲进行一些令人讨厌的处理,然后在将缓冲区释放到浏览器之前对其进行编辑......但这个问题的真正解决方案是更好地将您的数据与您的数据分开模板(MVC 模式值得一看)。

标签: php html include title


【解决方案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:正如诺曼建议的那样,你可以先在index.php的开头include 'myfile.php';,然后在body标签内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();
?>

【讨论】:

  • 您自己的解决方案有效。但是,它是如何工作的。请你给我解释一下好吗?
  • 包含myfile.php时,输出html部分。我使用 ob_* 函数将其捕获到一个变量中,而不是让它被打印出来,仅此而已。 ob_start() 打开输出缓冲,ob_get_contents() 获取存储在缓冲区中的字符串,ob_end_clean() 清理输出缓冲区然后关闭输出缓冲。
  • 感谢您的解释。祝你有美好的一天!
  • This 就是一个例子。希望这有帮助。 P.S:哦,没注意到你的评论。
【解决方案2】:

还有另一种方法:

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

【讨论】:

  • 不太明白你的意思。请把它嵌入我的代码中好吗!?
  • 你的意思是说你想把&lt;p&gt;Here's some content on the site I included!&lt;/p&gt;显示到正文中?对吗?
  • 是的,这正是我的意思。
  • 你应该像$con = "&lt;p&gt;Here's some content on the site I included!&lt;/p&gt;"; 那样做,然后将其回显到正文中。这是唯一的方法。
  • 您的意思是:我将包含两个变量,$title 和 $content。 echo $title; 在 html 标题标签中,echo $content; 在 html 正文中。对吗?
猜你喜欢
  • 1970-01-01
  • 2016-03-05
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2011-11-28
相关资源
最近更新 更多