PHP capture print/require output in variable
<p>Is it possible to add the output of print() to a variable?</p>

<p>I have the following situation:</p>

<p>I have a php file which looks something like this:</p>

<p><strong>title.php</strong></p>

<pre><code>&lt;?php

$content = '&lt;h1&gt;Page heading&lt;/h1&gt;';

print($content);
</code></pre>

<p>I have a php file which looks like this:</p>

<p><strong>page.php</strong></p>

<pre><code>&lt;?php

$content = '&lt;div id="top"&gt;&lt;/div&gt;';
$content.= $this-&gt;renderHtml('title.php');

print($content);
</code></pre>

<p>I have a function <code>renderHtml()</code>:</p>

<pre><code>public function renderHtml($name) {
    $path = SITE_PATH . '/application/views/' . $name;

    if (file_exists($path) == false) {
        throw new Exception('View not found in '. $path);
        return false;
    }

    require($path);
}
</code></pre>

<p>When I dump the content variable in page.php it doesn't contain the content of title.php. The content of title.php is just printed when it is called instead of added to the variable.</p>

<p>I hope it is clear what I am trying to do. If not I'm sorry and please tell me what you need to know. :)</p>

<p>Thanks for all your help!</p>

<p>PS</p>

<p>I have found that there was already a question like mine. But it was regarding the Zend FW.</p>

<p><a href="http://stackoverflow.com/questions/3805512/how-to-capture-a-zend-view-output-instead-of-actually-outputting-it">How to capture a Zend view output instead of actually outputting it</a></p>

<p>However I think this is exactly what I want to do.</p>

<p>How should I setup the function so that it behaves like that?</p>

<p><strong>EDIT</strong></p>

<p>Just wanted to share the final solution:</p>

<pre><code>public function renderHtml($name) {
    $path = SITE_PATH . '/application/views/' . $name;

    if (file_exists($path) == false) {
        throw new Exception('View not found in '. $path);
        return false;
    }

    ob_start();
    require($path);
    $output = ob_get_clean();

    return $output;
}
</code></pre>
