我正在努力让我的生活更轻松,并使所有页面都具有来自一个文件的相同页脚和标题内容,这就是我目前所拥有的:
包含内容的页面
<?php
include ("content.php");
echo $page_header;
?>
<div id="content">
</div>
<?php
echo $page_footer;
?>
content.php
<?php
// This is the header which we want to have on all pages
$page_header = include ("resources/content/header.php");
// This is the footer which we want on all pages
$page_footer = include ("resources/content/footer.php");
?>
Header.php 示例
<html>
<head>
<title>This is my title</title>
</head>
<body>
<div id="logo">
</div>
Footer.php 示例
<div id="footer">Copyright to me!</div>
</body>
</html>
我遇到的问题是我的 header.php 内容没有全部显示并导致页面格式出现问题。 header.php 确实包含一些 php if
语句和一些内联 javascript...这有关系吗?
有更好的方法吗?
请注意:我在本地使用 PHP 5,我的服务器是 PHP 4,所以答案需要对两者都有效
最佳答案
一种方法是为此使用输出缓冲函数。
更改content.php文件:
ob_start();
include ("resources/content/header.php");
$page_header = ob_get_clean();
ob_start();
include ("resources/content/footer.php");
$page_footer = ob_get_clean();
ob_start()
函数为任何输出创建一个临时缓冲区,然后 include()
使其不输出到页面响应,而是输出到由 ob_start()
创建的缓冲区。 ob_get_clean()
收集缓冲区的内容,销毁它并将收集的数据作为字符串返回。
@u_mulder 提到的另一种方法是在需要的地方简单地include()
那些文件。
更改页面内容文件:
<?php include ("resources/content/header.php"); ?>
<div id="content">
</div>
<?php include ("resources/content/footer.php"); ?>
但是在某些时候您可能需要一些复杂的模板处理引擎。有很多用于 php 的。
关于php - 添加大量 html 和 php 内容作为 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18941636/