0

在 PHP 中有一种情况,我需要主要执行页面,但是在该页面的输出中插入了一个项目。

我认为输出缓冲可能会有所帮助,但我不知道如何在我的情况下实现它。

我的代码如下所示:

//this document is part of a global functions file

function pageHeader (){

    //I'm using $GLOBALS here because it works, however I would really rather a better method if possible
    $GLOBALS['error_handler'] = new ErrorHandler(); //ErrorHandler class sets a function for set_error_handler, which gets an array of errors from the executed page

    require_once($_SERVER['DOCUMENT_ROOT'].'/sales/global/_header.php');

    //I would like the unordered list from ->displayErrorNotice() to be displayed here, but if I do that the list is empty because the list was output before the rest of the document was executed
}

function pageFooter (){

    $GLOBALS['error_handler'] ->displayErrorNotice(); //this function displays the errors as an html unordered list

    include($_SERVER['DOCUMENT_ROOT']."/sales/global/_footer.php");
}

网站上的大多数页面都包含此文档并使用pageHeader()pageFooter()功能。我想要实现的是在包含 _header.php 之后将 PHP 生成的错误的无序列表放入 HTML 列表中。如果我把它放在页脚(在文档执行之后),我可以让列表按预期工作,但我不希望它在那里。我想我可以用 JS 移动它,但我认为必须有一个 PHP 解决方案。

更新

我想知道ob_start()通过正则表达式搜索缓冲区的回调函数将错误列表放在哪里,然后将其插入将成为解决方案。

更新 2我已经解决了这个问题,我的答案如下。当我被允许时,我会在 2 天内接受它。

4

2 回答 2

1

终于解决了。关键是缓冲输出,并在缓冲区中搜索给定的 html 片段,并将其替换为无序列表。

我的实现是这样的:

function outputBufferCallback($buffer){

    return str_replace("<insert_errors>", $GLOBALS['error_handler']->returnErrorNotice(), $buffer);
}

function pageHeader (){

    ob_start('outputBufferCallback');
    //I'm using $GLOBALS here because it works, however I would really rather a better method if possible
    $GLOBALS['error_handler'] = new ErrorHandler(); //ErrorHandler class sets a function for set_error_handler, which gets an array of errors from the executed page

    require_once($_SERVER['DOCUMENT_ROOT'].'/sales/global/_header.php');

    echo '<insert_errors>'; //this snippet is replaced by the ul at buffer flush
}

function pageFooter (){

    include($_SERVER['DOCUMENT_ROOT']."/sales/global/_footer.php");
    ob_end_flush();
}
于 2012-01-19T03:25:17.657 回答
0

如果我做对了,您正试图在页眉和页脚之间插入一些计算出的代码/错误。我猜错误在页面的最后被汇总/总结,并将在页面页脚之后完成。

如果这是真的,我无论如何都想不出用纯 php 来做到这一点。它只能通过一个页面一次,并且不能双回。您可以做的是在页脚之后创建一个元素并使用 javascript 将其移动到您要显示它的区域。这将是我认为最简单的方法。您可以使用 jquery 轻松完成此操作。

如果我在正确的轨道上,我可以进一步解释,但我不是 100% 确定你在问什么......

您将使用的 jquery 命令是 .appendTo()。

于 2012-01-19T02:14:14.220 回答