PHP Tip: Output Control Functions
by Damian Manifold on January 23rd, 2008 in CodingOver the last year or so I’ve been getting used to programming in PHP, and I’ve long been at a stage when I can say my PHP skills are as good if not better than my skills in ASP.NET or ASP, an that I can accomplish more or less anything I need to in PHP.
However I would not say that I know PHP inside out, there are many function around the margins that you would not use day to day that might be very useful. There are times when I need to do things that send me trawling though the PHP site to find anything that will make the task possible or at least a little easier. But as with anything if you don’t use it regular you will soon forget what you can do and you have to research it again the next time.
Here I plan to document everything that I discover, no matter how little as a quick reference for me, and hopeful some sort of help to others.
I do a lot of work with WordPress which involves using its API. This can be a little frustrating sometimes, nothing more so that when you find the feature you need to it outputs directly to the screen, and there is no alternate function that allows you to execute the function into a variable. A couple of functions like this are next_posts_link and previous_posts_link that are used to display next and previous buttons on the site. For me they work fine individually and only display is needed, but I’d like to know if neither are shown so i can do something else. After trawling the API for an alternative and finding nothing, and not wanting to write a non API solution that may not be compatible with future release, I fell upon a kludgy but very workable solution.
PHP has a set of output control functions that allow interception of any screen output into a buffer. There are many function in this section that maybe useful, but the ones i found useful are
- ob_start: which start the interception of all output.
- ob_get_contents: that lets you read all the buffered output up to this point into a variable.
- ob_end_clean: that finishes the buffering of the out put.
Here is an example of how I used these commands to solve the WordPress problem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ob_start(); next_posts_link('« Previous'); $previous = ob_get_contents(); ob_end_clean(); ob_start(); previous_posts_link('Next »'); $next = ob_get_contents(); ob_end_clean(); ?> |



















