0

我正在尝试在多个页面的特定位置(例如,页面' page.php')。

基本上我的目标是有一个系统,其中

  • 我设置了逻辑(在'logic.php'文件中),所需的功能(在'functions.php'中),模板(在'template-file-for-output.php'中)

  • 我的同事可以使用它创建他们想要的任何页面(就像在'page.php'中的例子一样)他们想要的内容和HTML,只需要包含functions.php和logic.php文件他们文件的开头,以及 echo 语句以在他们希望的位置显示动态内容。

我遇到的问题是,当我测试这个示例并尝试在“page.php”中实现这一点时,我总是从页面中获取自定义 HTML 之前的内容。我想它与输出缓冲有关,这包括在 outputContent 函数中,我尝试了其他方法但没有成功。

这里是文件的内容:

  • 逻辑.php:
$submitOK = false;

if ($submitOK === true) {
    /** No errors, output the error free content */
    $output = outputContent($var);
} else {
    /** Errors, output the content with errors */
    $output = outputContent($var, $errors);
}
  • 函数.php:
function outputContent($var, $errors = null)
{
    extract($var);

    ob_start();
    include 'template-file-for-output.php';
    $output = ob_get_contents();
    ob_get_clean();
    return $output;
}
  • 模板文件for-output.php:
<p>Some content with tags and so on, filled in by some values of the $var array.</p>
<p>Example with the $example variable extracted from $var <?php echo $example; ?></p>
<p>Another variable also from $var <?php echo $anotherVariable; ?>
  • 页面.php:
<?php

include 'logic.php';
include 'functions.php';

?>
<!DOCTYPE html>
<html>
    <head><title>A page of the site</title></head>
    <body>
        <p>Something interesting (hopefully).</p>
        <?php echo $output; ?>
    </body>
</html>
4

2 回答 2

1

将 ob_get_contents 更改为 ob_get_clean,ob_get_contents 获取缓冲区的内容但保持原样。您之前的代码为缓冲区分配了一个变量,然后将缓冲区刷新到输出。

function outputContent($var, $errors = null)
{
    extract($var);

    ob_start();
    include 'template-file-for-output.php';
    $output = ob_get_clean();
    return $output;
}
于 2013-07-30T15:57:26.990 回答
0

暂且不说,目前有模板系统已经相当有效地解决了这个问题......

我会尝试不包含模板文件,而是使用 file_get_contents 读取文件,然后在输出缓冲部分中将其回显。

function outputContent($var, $errors = null)
{
    extract($var);

    ob_start();
    echo file_get_contents('template-file-for-output.php');
    $output = ob_get_clean();
    return $output;
}
于 2013-07-30T16:02:09.690 回答