Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP capture print/require output in variable

Tags:

php

Is it possible to add the output of print() to a variable?

I have the following situation:

I have a php file which looks something like this:

title.php

<?php

$content = '<h1>Page heading</h1>';

print($content);

I have a php file which looks like this:

page.php

<?php

$content = '<div id="top"></div>';
$content.= $this->renderHtml('title.php');

print($content);

I have a function renderHtml():

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);
}

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.

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. :)

Thanks for all your help!

PS

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

How to capture a Zend view output instead of actually outputting it

However I think this is exactly what I want to do.

How should I setup the function so that it behaves like that?

EDIT

Just wanted to share the final solution:

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;
}
like image 530
PeeHaa Avatar asked Dec 04 '22 09:12

PeeHaa


2 Answers

You can capture output with the ob_start() and ob_get_clean() functions:

ob_start();
print("abc");
$output = ob_get_clean();
// $output contains everything outputed between ob_start() and ob_get_clean()

Alternatively, note that you can also return values from an included file, like from functions:

a.php:

return "<html>";

b.php:

$html = include "a.php"; // $html will contain "<html>"
like image 113
Arnaud Le Blanc Avatar answered Dec 19 '22 11:12

Arnaud Le Blanc


You can use output buffering to capture any output send ob_start() http://us3.php.net/ob_start. You capture the output with ob_get_flush() http://us3.php.net/manual/en/function.ob-get-flush.php.

Or you could just return the output from title.php like so:

<?php

$content = '<h1>Page heading</h1>';
return $content;
like image 22
Wade Avatar answered Dec 19 '22 11:12

Wade