I'm a fairly experienced PHP coder, and am just wondering what the best way of echoing large chunks of HTML code is (best practise).
Is it better to do this:
<?php
echo "<head>
<title>title</title>
<style></style>
</head>";
?>
or this:
<?php
define("rn","\r\n");
echo "<head>".rn
."<title>title</title>".rn
."<style></style".rn
."</head>".rn;
?>
I tend to use the second as it doesn't mess up indenting in the php source. Is this the way most people do it?
Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables. Using echo shorthand or separating HTML: PHP echo shorthand can be used to display the result of any expression, value of any variable or HTML markup.
'; $content = file_get_contents('html/welcome. html'); $pagecontent = str_replace('[[content]]', $content, $page); echo($pagecontent); Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
The PHP print Statement You can also use the print statement (an alternative to echo ) to display output to the browser. Like echo the print is also a language construct not a real function. So you can also use it without parentheses like: print or print() .
IMO, The best way is typically to store the HTML separately in a template file. This is a file that typically contains HTML with some fields that need to get filled in. You can then use some templating framework to safely fill in the fields in the html document as needed.
Smarty is one popular framework, here's an example how that works (taken from Smarty's crash course).
Template File
<html>
<head>
<title>User Info</title>
</head>
<body>
User Information:<p>
Name: {$name}<br>
Address: {$address}<br>
</body>
</html>
Php code that plugs name & address into template file:
include('Smarty.class.php');
// create object
$smarty = new Smarty;
// assign some content. This would typically come from
// a database or other source, but we'll use static
// values for the purpose of this example.
$smarty->assign('name', 'george smith');
$smarty->assign('address', '45th & Harris');
// display it
$smarty->display('index.tpl');
Aside from Smarty there's dozens of reasonable choices for templating frameworks to fit your tastes. Some are simple, many have some rather sophisticated features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With