87

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?

8 Answers 8

121

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Also the <<<HTML heredoc identifier must not be indented, that is if it does not have something such as "return" in front of it.
it can be indented as much as you like, but should have a newline right after the identifier.
You can avoid braces if the var is non into an array: <h1>$replStr</h1> or <h1>{$array['var]}</h1>
103

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

7 Comments

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 first
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'); ?>
@Joren Because that's explicitly what the OP doesn't want.
Ok, so if you wanted to echo it, my example would be the way to go?
@Joren Yes, essentially.
|
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.

3 Comments

/mindblown can you explain why this works when all else failed?
this works fine without echo, just ?> html <?php. Check the fiddle
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!
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');
}

1 Comment

Winging some old PHP code. This is solid, thanks! I had to use Smarty's display method instead of render.
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;

}

1 Comment

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? Thanks
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 :)

1 Comment

file_get_contents(): Filename cannot be empty. How should this suppose to work?
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));
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.