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

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

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

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

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

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

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

使用output buffering:

<?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();