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

I have a PHP function that I use to output a standard HTML block. Currently, it looks like this:

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

I want to return (not echo) the HTML inside the function. Is there a way to do this without creating the HTML (top) in the line?

+48
string php templating
Feb 09 '09 at 14:52
source share
5 answers

You can use heredoc , which supports variable interpolation, making it pretty neat:

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

Pay attention to the warning in the manual, however - the closing line should not contain spaces, therefore, you can not indent.

+70
Feb 09 '09 at 15:02
source share

Yes there is: you can capture the text echo ed using ob_start :

 <?php function TestBlockHTML ($replStr) { ob_start(); ?> <html> <body><h1> <?php echo ($replStr) ?> </h1> </html> <?php return ob_get_clean(); } ?> 
+53
Feb 09 '09 at 14:55
source share

This may be a sketchy solution, and I would appreciate if anyone would indicate if this is a bad idea, as this is not a standard use of functions. I managed to get HTML from a PHP function without creating a return value as a string with the following:

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

Just a "call" function:

 noStrings(); 

And he will output:

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

Using this method, you can also define PHP variables inside a function and derive them from HTML.

+13
Nov 13 2018-11-11T00:
source share

Create a template file and use the template engine to read / update the file. This will increase the reliability of your code in the future, as well as a separate display from the logic.

Smarty example:

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> 

the code

 function TestBlockHTML(){ $smarty = new Smarty(); $smarty->assign('title', 'My Title'); $smarty->assign('string', $replStr); return $smarty->render('template.tpl'); } 
+5
09 Feb '09 at 15:32
source share

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

PATTERN 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; } 
+2
Feb 28 '14 at 18:38
source share



All Articles