I have a PHP function that I\'m using to output a standard block of HTML. It currently looks like this:
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.
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');
}
<h1>{title}</h1>
<div>{username}</div>
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
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;
}
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 :)
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));
}