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

时间:2015-02-20 12:06:06

标签: php html apache dom

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

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

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

2 个答案:

答案 0 :(得分:3)

使用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();

潜在问题

潜在的用户影响(取决于您的网络服务器)您的页面输出会在输出时流式传输到用户的浏览器(为什么您可以在他们之前开始看到非常大的页面&#39 ;完成装载)。但是如果你使用输出缓冲区,用户只有在你停止缓冲并输出后才会看到结果。

另外,因为您正在缓冲而不是流式传输服务器,所以需要存储您正在缓冲的内容,这会耗尽额外的内存(除非您生成超过超出大页面的内容,否则不会出现问题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();

答案 1 :(得分:1)

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

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