开发者

PHP Output Buffer Content

开发者 https://www.devze.com 2023-04-05 08:39 出处:网络
I\'m using PHP to create user-agent based dynamic stylesheets with: AddHandler application/x-httpd-php .css

I'm using PHP to create user-agent based dynamic stylesheets with:

AddHandler application/x-httpd-php .css

And I send them to client using gzip (php.ini based):

output_handler = ob_gzhandler

But I also want to minify the content of my dynamic stylesheets in order to get better performances... so, at the end of my stylesheet I put:

input.confirmation
{
<?php if ($Browser == 'lt8') { ?>
    margin-top: 1px;
<?php } else { ?>
    margin-top: 3px;
<?php } ?>
}
<?php echo Minify(ob_get_clean()); ?>

Where "function Minify($CSSCode)" just returns a minified version of the string I put in the argument. The problem is that this just outputs an empty stylesheet. I also tried the following code:

<?php
    $Content = ob_get_contents();
    ob_clean();
    echo Minify($Content);
?>

But I obtain the same result: empty file. If I use instead:

<?php echo Minify(ob_get_contents()); ?>

My shylesheet will contain both unminified and minified code. A solution I thought about is to concatenate every single stylesheet line inside a variable and print it in the end like this:

$CSSCode  = '';
[...]
$CSSCode .= "#header";
$CSSCode .= "{";
$CSSCode .= "  display: block;";
$CSSCode .= "  height: 100px;";
$CSSCode .= "}";
[...]
echo Minify($CSSCode);

But I would prefer to avoid this practice because:

  1. It will be a real nightmare to modify my CSS after, if needed.
  2. I have only one stylesheet for my whole website and it's quite long... so transforming it into a variable based st开发者_开发百科ylesheet risks to be really really time expensive.

How can I properly clear and override the output buffer?

Thanks in advance!


What you can do is to do an explicit ob_start() again in the beginning of the script so you get a second buffer as they can be nested. In general the compression should take good care of the whitespaces so the gain of the Minify operation should be barely notable in the end.

As a remark: When generating CSS etc. from a script make sure to set proper cache expiration headers so the client won't request the CSS files everytime but caches them. This brings a way bigger gain than any of the other things you can do.


after ob_start, you must ob_end_clean (or use one of its variants), or else the Output Buffering is still ON, and no content will be outputted. =)

http://php.net/manual/en/function.ob-end-clean.php

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号