Is there any way to return HTML in a PHP function? (without building the return value as a string)


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) { ?>
    <body><h1> <?php echo ($replStr) ?> </h1>
<?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?

2/19/2016 5:31:04 PM

Accepted Answer

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

function TestBlockHTML ($replStr) {
return <<<HTML

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

3/15/2012 8:17:41 PM

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

<?php function TestBlockHTML ($replStr) { ob_start(); ?>
    <body><h1> <?php echo ($replStr) ?> </h1>
    return ob_get_clean();
} ?>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow