End User Posted June 1, 2010 Share Posted June 1, 2010 Maybe people here have seen this trick before, maybe not. I found it to be very useful in a variety of situations, so I thought I'd post it here. Normally when you use include() or require(), the results of the code or HTML from the included file is spit out right where the include() is done. But by using PHP's object buffer you can include the file and save the contents to a variable for use later. You can take the variable and fiddle with it all you want (do a search and replace on the contents, do transforms on it, or just save it to use later on in the page). You could also use this to avoid having to include() a file multiple times. I use this for loading template files ahead of time in some of my projects, or loading a table with some placeholders that I populate based on the results of some later code. To read an include() or require() file into a variable, use output buffering: // start the bufferingob_start(); // include the fileinclude( '/home/user/htdocs/some_page.php');// create a variable from the buffer contents$saved_output = ob_get_contents();// stop the bufferingob_end_clean(); // and here's the variable with all of the output from 'some_page.php':print $saved_output; It wasn't immediately apparent to me how this trick might be used, but after a little thought I found a number of instances where it came in very handy. I hope someone here also finds this useful. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.