php - 添加大量 html 和 php 内容作为 PHP 变量

标签 php html css include

我正在努力让我的生活更轻松,并使所有页面都具有来自一个文件的相同页脚和标题内容,这就是我目前所拥有的:

包含内容的页面

<?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/

相关文章:

css - 你如何在CSS中制作渐变背景?

javascript - 为什么我的工具提示没有显示?

html - 在 Twitter Bootstrap 的导航按钮之间放置居中文本

php - 从 mssql 触发器运行 php 脚本

php - 为什么这个 ajax 帖子给我一个错误? ajax post是否需要返回 "true"或 "false"?

php/sql JOIN 从下拉选择中创建的 $variable 中的两个数据表

javascript - JS - 滚动悬停相关的 div

php使用insert语句添加到数据库

javascript - CSS 分离头表技巧 : keep verticall scrollbar on screen and last cell go full width

javascript - 如何以编程方式单击从另一个页面加载的按钮?