【问题标题】:Adding a large amount of html and php content as PHP variable添加大量 html 和 php 内容作为 PHP 变量
【发布时间】:2013-09-22 07:59:48
【问题描述】:

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

包含内容的页面

<?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,所以答案需要对两者都有效

【问题讨论】:

  • include ("resources/content/footer.php"); 而不是将其分配给变量
  • 这种技术真的没有什么问题,你试过验证你的 HTML 吗?没有任何理由某些条件 php 或内联 JS 应该有所作为,您可以发布 header.php 内容
  • 我在类似的问题here 中写过这个。
  • @mdesdev 甚至与我的问题无关。
  • 好的,但据我所知,您正在尝试创建母版页、相同的页眉、页脚等。内容多变,我的解决方案属于同一类别,除非您尝试不同的方法。

标签: php html css include


【解决方案1】:

一种方法是为此使用输出缓冲函数。

更改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有很多。

【讨论】:

  • 这很奏效!请您详细说明使用ob_start(); 优于include(); 的好处?
  • @AaronHatton 注意更新。没有任何好处。它只是阻止直接输出,并允许在作为对客户端浏览器的响应之前对其进行收集和预处理。
猜你喜欢
  • 2021-12-29
  • 2011-01-10
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
相关资源
最近更新 更多