Forum Moderators: coopster

Message Too Old, No Replies

String replacement AND compression

How to get PHP to compress a page while also doing string replacement.

         

JAB Creations

8:27 am on Jun 17, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm having trouble getting PHP to do string replacement and then compressing the output.

I start with:
ob_start('ob_gzhandler');


Then at the end of the code I use:
echo str_replace($find,$replace,ob_get_clean());


Unfortunately if I want to compress the output ob_end_flush() does not seem to like string replacement, ignoring it and outputting the code.

I also tried adding a second layer by opening another ob_start(); before the string replacement and then using ob_end_flush() twice which did not have the desired effect.

John

JAB Creations

9:31 am on Jun 17, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<?php
ob_start();//Start the initial buffer, do NOT use compression here.

//Content output here.

$c = str_replace($find,$replace,ob_get_contents());//String replacement.
ob_end_clean();//Close buffering.

ob_start('ob_gzhandler');//Start a fresh buffer with compression.
echo $c;//Output the original buffer.
ob_end_flush();//Send to the client.
?>

JorgeV

10:34 am on Jun 17, 2020 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



Hello,

'ob_gzhandler' is a special function, intended to send compressed data to the web browser. Therefor, it checks what compression algorithm the web browser supports. Also, if the header has already been sent, it will not compress the data. If this is part of a command line script, then, there are no compression either.

What are you exactly trying to do?

If you just want to compress a string, then use one of the compression functions : [php.net...]

JAB Creations

10:37 am on Jun 17, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I solved the problem and posted the working code. The issue was effecting the serving of some pages. Occasionally something has to be replaced before being sent to the client.

John