This article will summarize the implementation of php ob_start (ob_gzhandler) for web page compression and transmission. If you need it, please refer to it.
First, let's look at the usage of ob_start.
Use the PHP ob_start () function to open the browser cache. This ensures that the cache content will not be output before you call flush (), ob_end_flush () (or after the program is executed ).
The Code is as follows: |
Copy code |
<? Php Ob_start (); // open the buffer Phpinfo (); // use the phpinfo Function $ Info = ob_get_contents (); // obtain the buffer content and assign it to $ info Using file1_fopen('info.txt ', 'w'); // open the info.txt file. Fwrite ($ file, $ info); // write the information to info.txt Fclose ($ file); // close the info.txt file ?> |
PHP ob_start () functions have a great feature. You can also use the ob_start parameter to automatically run commands after the cache is written, such as ob_start ("ob_gzhandler "); the most common practice is to use ob_get_contents () to get the content in the cache.
The code below is an example of compressing a webpage. We use the ob_gzip function to compress the output content with ob_start and put it in the "buffer zone" before outputting it.
The Code is as follows: |
Copy code |
// Enable Compression If (function_exists ('ob _ gzip ')) { Ob_start ('ob _ gzip '); } // Prepare some content to be compressed For ($ I = 0; I I <100; $ I ++) { Echo ('here is the test content <br> '); } // Output compressed results Ob_end_flush ();
// This is the ob_gzip compression function. Function ob_gzip ($ content) { If (! Headers_sent () & extension_loaded ("zlib") & strstr ($ _ SERVER ["HTTP_ACCEPT_ENCODING"], "gzip ")){ $ Content = gzencode ($ content, 9 ); Header ("Content-Encoding: gzip "); Header ("Vary: Accept-Encoding "); Header ("Content-Length:". strlen ($ content )); } Return ($ content ); } |