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) { ?>
    <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?


Solution 1:

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

function TestBlockHTML ($replStr) {
return <<<HTML
    <html>
    <body><h1>{$replStr}</h1>
    </body>
    </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.

Solution 2:

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

Solution 3:

This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:

function noStrings() {
    echo ''?>
        <div>[Whatever HTML you want]</div>
    <?php;
}

The just 'call' the function:

noStrings();

And it will output:

<div>[Whatever HTML you want]</div>

Using this method, you can also define PHP variables within the function and echo them out inside the HTML.