Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save an include's output to a string? [duplicate]

Tags:

php

Possible Duplicate:
Storing echoed strings in a variable in PHP

Suppose I have

<?php include "print-stuff.php"; ?>

print-stuff.php contains PHP/HTML template, which means that when it is included, HTML gets printed. Is there any way to capture that HTML as a string, so that I may save it to use elsewhere?

Moving the include statement elsewhere is not an option, because print-stuff.php also performs logic (creates/modifies variables) that the surrounding code depends on. I simply want to move the file's output, while leaving its logic as is.

like image 494
Steve Avatar asked Aug 17 '09 15:08

Steve


2 Answers

You can Output Buffer it to make sure the HTML isn't shown and is instead put into a variable. (PHP will still run, but HTML output will be contained in the variable)

ob_start();
include "print-stuff.php";
$contents = ob_get_contents();
ob_end_clean();

....

like image 177
Tyler Carter Avatar answered Sep 20 '22 16:09

Tyler Carter


Honestly I came on here and went ah-ha, I know the answer to this!!! Then I looked down and saw other people got to it before I did.

But, for the heck of it, I do like this:

ob_start();
include 'something.php';
$output = ob_get_contents();
ob_end_clean();
like image 32
Daniel Avatar answered Sep 21 '22 16:09

Daniel