我正在努力使我的生活更轻松,并使所有页面具有来自一个文件的相同页脚和标题内容,这就是我到目前为止所拥有的:
包含内容的页面
<?php
include ("content.php");
echo $page_header;
?>
<div id="content">
</div>
<?php
echo $page_footer;
?>
内容.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");
?>
页眉.php示例
<html>
<head>
<title>This is my title</title>
</head>
<body>
<div id="logo">
</div>
页脚.php示例
<div id="footer">Copyright to me!</div>
</body>
</html>
我遇到的问题是我的标题.php内容并未全部显示并导致页面格式问题。标头.php确实包括一些php if
语句和一些内联javascript...这应该重要吗?
有没有更好的方法?
请注意:我在本地使用 PHP 5,我的服务器是 PHP 4,所以答案需要同时适用于两者
一种方法是为此使用输出缓冲函数。
更改内容.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的。