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

8

85

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?

Japheth answered 9/2, 2009 at 14:52 Comment(0)
A
120

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.

Archives answered 9/2, 2009 at 15:2 Comment(3)
Also the <<<HTML heredoc identifier must not be indented, that is if it does not have something such as "return" in front of it.K2
it can be indented as much as you like, but should have a newline right after the identifier.Archives
You can avoid braces if the var is non into an array: <h1>$replStr</h1> or <h1>{$array['var]}</h1>Byproduct
R
101

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();
} ?>
Rotation answered 9/2, 2009 at 14:55 Comment(6)
Exactly, this way syntax is highlighted and key words are colored as they would being normal HTML, other than being content in a string. Definitely a better answer for maintainability, which should always come firstFellatio
Why would you use the output buffer when this seems to work fine? <?php function outputHTML($string) { ?> <h1><?php echo $string; ?></h1> <p>Lorem ipsum dolar</p> <? } ?> <?php outputHTML('A is for Apple'); ?> <?php outputHTML('B is for Ball'); ?>Knipe
@Knipe Because that's explicitly what the OP doesn't want.Rotation
Ok, so if you wanted to echo it, my example would be the way to go?Knipe
@Knipe Yes, essentially.Rotation
This is perfect. You can even include echo statements after ob_start and it is included in ob_get_clean()'s output. I am writing modules for a third-party script, and it forces you to put all of the output for the page into a get() function. This is a lifesaver.Damiano
U
19

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.

Ury answered 13/11, 2011 at 0:23 Comment(3)
/mindblown can you explain why this works when all else failed?Cosmism
this works fine without echo, just ?> html <?php. Check the fiddleCholla
At least in PHP 8.1.12 on Windows, keep in mind that you need whitespace after the <?php on line 4. Without it, PHP throws error Unclosed '{' on line 4. Also note that this SO question technically asks for a way to return output, but this solution echos it!Anandrous
P
9

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">
<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');
}
Pravit answered 9/2, 2009 at 15:32 Comment(1)
Winging some old PHP code. This is solid, thanks! I had to use Smarty's display method instead of render.Andiron
M
5

Another way to do is is to use file_get_contents() and have a template HTML page

TEMPLATE PAGE

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

PHP Function

function YOURFUNCTIONNAME($url){

$html_string = file_get_contents($url);
return $html_string;

}
Modular answered 28/2, 2014 at 18:38 Comment(1)
This is the closest to what I'm looking for. @Cayde 6, do you think theres a way to have a single file 'template.php', containing both the php function and html? So then anywhere in my site, I just 'require_once('template.php')', then call echo the function wherever I need that html to appear. In the YOURFUNCTIONNAME($url), would the $url would need to be itself? How can we do that? ThanksWhitelaw
D
0

Or you can just use this:

<?
function TestHtml() { 
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->

<? } ?>

to get content from this function , use this :

<?= file_get_contents(TestHtml()); ?>

That's it :)

Dessalines answered 11/6, 2018 at 18:35 Comment(1)
file_get_contents(): Filename cannot be empty. How should this suppose to work?Opalopalesce
I
0

If you don't want to have to rely on a third party tool you can use this technique:

function TestBlockHTML($replStr){
  $template = 
   '<html>
     <body>
       <h1>$str</h1>
     </body>
   </html>';
 return strtr($template, array( '$str' => $replStr));
}
Intellectualism answered 16/6, 2018 at 22:23 Comment(0)
L
0

Template File

<h1>{title}</h1>
<div>{username}</div>

PHP

if (($text = file_get_contents("file.html")) === false) {
    $text = "";
}

$text = str_replace("{title}", "Title Here", $text);
$text = str_replace("{username}", "Username Here", $text);

then you can echo $text as string

Labourer answered 13/6, 2020 at 5:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.