Making all PHP file output pass through a “filter file” before being displayed

后端 未结 5 1781
傲寒
傲寒 2020-12-17 02:43

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 b

相关标签:
5条回答
  • 2020-12-17 03:07

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

    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>
    

    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
    

    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.

    0 讨论(0)
  • 2020-12-17 03:07

    Have a look at using Smarty. It's a templating system for PHP, that is good practice to use, and into which you can plug global output filters.

    0 讨论(0)
  • 2020-12-17 03:16

    edit: Paul's reply is better. So it would be

    ob_start("my_filter_function");
    

    My original reply was:

    That can be achieved with output buffering.

    For example:

    ob_start();
    // Generate all output
    echo "all my output comes here."
    // Done, filtering now
    $contents = ob_get_contents();
    ob_end_clean();
    echo my_filter_function($contents);
    
    0 讨论(0)
  • 2020-12-17 03:24

    You can use output buffering and specify a callback when you call ob_start()

    <?php
    function filterOutput($str) {
        return strtoupper($str);
    }
    
    ob_start('filterOutput');
    ?>
    
    <html>
        some stuff
        <?php echo 'hello'; ?>
    </html>
    
    0 讨论(0)
  • 2020-12-17 03:24

    You can use PHP's output buffering functions to do that

    You can provide a callback method that is called when the buffer is flushed, like:

    <?php
    
    function callback($buffer) {   
        // replace all the apples with oranges  
        return (str_replace("apples", "oranges", $buffer)); 
    }
    
    ob_start("callback");
    ?>
    <html>
    <body>
        <p>It's like comparing apples to oranges.</p>
    </body>
    </html>
    
    <?php
    ob_end_flush();
    ?>
    

    In that case output is buffered instead of sent from the script and just before the flush your callback method is called.

    0 讨论(0)
提交回复
热议问题