使所有 PHP 文件输出通过“过滤文件"在显示之前

2021-12-23 00:00:00 filter php

有没有办法让我的所有 PHP 和/或 HTML 文件输出在显示在浏览器中之前被过滤"?我想我可以在它显示之前通过一个全局函数传递它,但我被困在实现上.请帮忙.

Is there any way for all my PHP and/or HTML file output to be "filtered" before being displayed in the browser? I figured that I could pass it through a global function before it is displayed but I'm stuck on the implementation. Please help.

如果有更好的方法来实现相同的结果,我很乐意知道.

If there is a better way to achieve the same result, I'd be happy to know.

谢谢.

推荐答案

查看 ob_start 它可以让您通过用于后处理脚本输出的回调处理程序.

Check out ob_start which lets you pass a callback handler for post-processing your script output.

例如,PHP 包含一个内置回调 ob_gzhandler 用于压缩输出:

For example, PHP includes a built-in callback ob_gzhandler for use in compressing the output:

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>

这是一个更完整的示例,说明如何使用 tidy 扩展:

Here's a fuller example illustrating how you might tidy your HTML with the tidy extension:

function tidyhtml($input)
{
    $config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

    $tidy = new tidy;
    $tidy->parseString($input, $config, 'utf8');
    $tidy->cleanRepair();

    // Output
    return $tidy;
}

ob_start("tidyhtml");

//now output your ugly HTML

如果您想确保所有 PHP 脚本使用相同的过滤器而不直接包含它,请查看 auto_prepend_file 配置指令.

If you wanted to ensure all your PHP scripts used the same filter without including it directly, check out the auto_prepend_file configuration directive.

相关文章