views:

2087

answers:

4

I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this:

<?php function TestBlockHTML ($replStr) { ?>
    <html>
    <body><h1> <?php echo ($replStr) ?> </h1>
    </html>
<?php } ?>

I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?

+7  A: 

Yes, there is: you can capture the echoed text using ob_start:

<?php function TestBlockHTML ($replStr) { ob_start(); ?>
    <html>
    <body><h1> <?php echo ($replStr) ?> </h1>
    </html>
<?php
    return ob_get_clean();
} ?>
Konrad Rudolph
+12  A: 

You can use a heredoc, which supports variable interpolation, making it look fairly neat:

function TestBlockHTML ($replStr) {
return <<<HTML
    <html>
    <body><h1>{$replStr}</h1>
    </html>
HTML;
}

Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.

Paul Dixon
Also the <<<HTML heredoc identifier must not be indented, that is if it does not have something such as "return" in front of it.
teh_noob
it can be indented as much as you like, but should have a newline right after the identifier.
Paul Dixon
haha i just used this in some code.
A: 

Make sure when using Paul's solution to have the closing line

HTML;

in a separate line with no leading spaces or tabs.

Mohamed Ali
+2  A: 

Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.

An example using Smarty:

Template File

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>

Code

function TestBlockHTML(){
  $smarty = new Smarty();
  $smarty->assign('title', 'My Title');
  $smarty->assign('string', $replStr);
  return $smarty->render('template.tpl');
}
Rob