如何在应用程序级别获得所有通过PHP生成的HTML代码


How to get all the HTML code generated via PHP at application-level

在PHP中,是否可以在请求处理结束时获取所有生成的HTML代码?

我想要实现的是能够检索(并且可能保存/缓存)即将发送给用户的实际HTML。我可以在ASP.net中使用Global.asax过滤器做类似的事情,它可以访问低级生成的html代码并修改/访问它

如果需要,我可以修改web服务器设置和/或php解释器设置(目前web应用程序运行在Apache+mod_php上)。

使用输出缓冲:

<?php
// Start buffering (no output delivered to the browser from now on)
ob_start();
// Generate the HTML
// ...
// Grab the buffer as a variable
$html_output = ob_get_contents();
// If you want to stop buffering and send the buffer to the browser
ob_end_flush();
// OR if you want to stop buffering and throw away the buffer
ob_end_clean();

潜在问题

这可能会对用户产生影响,因为(取决于您的web服务器)您的页面输出在输出时会流式传输到用户的浏览器(为什么您可以在加载完成之前开始看到非常大的页面)。但是如果你使用输出缓冲区,用户只有在你停止缓冲并输出后才能看到结果

此外,由于您正在缓冲而不是流式传输,您的服务器将需要存储您正在缓冲的内容,这将占用额外的内存(这不是问题,除非您生成的页面非常大,超过了PHP内存限制的内存限制)。

为了避免内存不足,您可以使用如下回调将缓冲区分块并以特定的分块大小写入磁盘(或刷新给用户):

<?php
// The callback function each time we want to deal with a chunk of the buffer
$callback = function ($buffer, $flag) {
    // Cache the next part of the buffer to file?
    file_put_contents('page.cache', $buffer, FILE_APPEND & LOCK_EX);
    // $flag contains which action is performing the callback.
    // We could be ending due to the final flush and not because
    // the buffer size limit  was reached. PHP_OUTPUT_HANDLER_END
    // means an ob_end_*() function has been called.
    if ($flag == PHP_OUTPUT_HANDLER_END) {
       // Do something different
    }
    // We could echo out this chunk if we want
    echo $buffer;
    // Whatever we return from this function is the new buffer
    return '';
};
// Pass the buffer to $callback each time it reaches 1024 bytes
ob_start($callback, 1024)
// Generate the HTML
// ...
ob_end_clean();

我认为您想要使用的是输出缓冲!在页面的开头使用:ob_start();在页面的末尾,您可以使用以下内容发送到客户端/浏览器:ob_end_flush();

在发送之前,您可以将该缓冲区记录到数据库或文本文件