ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Having fun with PHP’s output buffer

(Page 3 out of 3)

Creating your own HTML tags

With output buffering it's also possible to create your own HTML tags, and in fact, that's how my PHP Components work. Like the output replace function, this is also done with a callback function. The example below demonstrates a simple HTML tag:

function my_htmltag($content) {
        // Replace my tag
        $content = str_replace ('', '', $content);
        $content = str_replace ('', '
', $content);

        return $content;
}

// Start output buffer with our callback
ob_start('my_htmltag');

echo 'Hello World';

?>

(View Live Demo)

As you can see, in the above example we created a new tag called 'mytag', and it actually represents the strong and em tags. When you have a look at the live demo, you'll notice that the client will never see your own HTML tags, and all they see are real HTML tags. This means that it works in any browser.

Of course the above example is very simple, and much more is possible. My own PHP components usually use a regular expression to get the tag, then parse the tag and any sub tags using a HTML parser. But this is beyond the scope of this article (maybe something for a future article).

Enabling GZip compression

Output buffering also makes it possible to enable GZip compression on-the-fly, which can lead to huge bandwidth and cost savings. All it takes is using the special ob_gzhandler() callback function, like so:

// Start GZip compression
ob_start('ob_gzhandler');

echo 'This is compressed on-the-fly with the GZip library';

?>

(View Live Demo)

Be aware though that you must have the zlib library installed for this to work. The best way to make sure that it's installed is by using the following code:

// Start GZip compression (if the ob_gzhandler function exists)
if (function_exists('ob_gzhandler')) {
        ob_start('ob_gzhandler');
}

echo 'This is compressed on-the-fly with the GZip library';

?>

This basically makes sure the callback function actually exists, so that you don't get any problems.

Also make sure that your own callback functions are capable with the gzip callback. If the ob_start() with your callback function is before the ob_start() with the ob_gzhandler callback, your callback function will receive compressed content, which means it needs to first uncompress the content, and when it's done with it, compress it again. The code to do this looks like this:

// Define the gzdecode function
if (!function_exists('gzdecode')) {
        function gzdecode ($data) {
                // Check if data is GZIP'ed
                if (strlen($data) < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
                        return false;
                }

                // Remove first 10 bytes
                $data = substr($data, 10);

                // Return regular data
                return gzinflate($data);
        }
}

function mycallback($buffer) {
        // GZipped buffer?
        $gzbuffer = gzdecode($buffer);
        if ($gzbuffer !== false) {
                $buffer = $gzbuffer;
        }

        $buffer = str_replace ('Dennis Pallett', 'John Doe', $buffer);

        // Return normal or GZipped buffer
        return ($gzbuffer !== false) ? gzencode($buffer) : $buffer;
}

ob_start('mycallback');
ob_start('ob_gzhandler');

echo 'My name is Dennis Pallett';

?>

(View Live Demo)

Read more about this problem in this blog entry.

Conclusion

In this article I've taken you through most of the functions and features of output buffering. Output buffering is really an amazing feature of PHP, and it really gives you complete control of your PHP scripts and its output. I've never used an output replace function before, but there have been times where I wished I had it.

In a future article I will take a look at creating your own full-blown PHP components, similar to PHP:Form and PHP:DataGrid so stay tuned to PHPit.

If you have any questions or comments on this article, leave them in the comments or join us at PHPit Forums.

« Previous: Output replace function



7 Responses to “Having fun with PHP’s output buffer”

  1. Piku’s PHP Blog » PHPit: Having fun with PHP’s output buffer Says:

    […] In this article Dennis Pallett explains what the output buffer is, how to use it, and shares some neat tricks possible with the output buffer. Samples and demo code included. […]

  2. Sam’s random musings » PHPit.net: Having fun with PHP’s output buffer Says:

    […] One of the more powerful and handy features that PHP offers is output buffering. It allows you more control over when the client’s browser gets the information instead of just spewing information at random. It is a little tricky to get the hang of, so PHPit.net has put together this new tutorial on how to get started. […]

  3. sam Says:

    Hi i’ve heard that its possible to output to the browser while the script is still running(like search query) using some buffer and/or flush function.if u can write or direct me towards such links it would be immensly helpful

  4. Andy W Says:

    Excellent this really helped me understand, the headers all ready sent error is a nightmare when coding in PHP by understanding and using output buffering all my scripts redirect as they should.

    Thanks guys.

  5. MA Razzaque Rupom Says:

    Output buffer compression to save bandwidth is a good option. Nice to see this type of writting in this site.
    Regards,
    [Rupom]

  6. PHPit - Totally PHP » Create your own HTML widgets with PHP Says:

    […] But with a little help from PHP, we can still create our own HTML tags, and have it working in all browsers. In this tutorial I will show you how. First we’ll go through the basics of creating a new tag, and after that we’ll explore some more advanced functionality. We’ll be making use of an output buffer to create our own tags, so if you’ve never used the output buffer before, it’s probably useful to read the following article first: Having fun with PHP’s output buffer. Let’s get started! […]

  7. Brian Cray Says:

    I have written a few articles about advanced PHP output buffering. Check them out at http://www.briancray.com/blog/view/25/

    If you look around my web site, you will find more articles about things to do with it.

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction & The Basics
  2. Output replace function
  3. Own HTML tags & GZip compression
Bookmark Article
Download Article
PDF
Download this article as a PDF file