Best way to echo HTML in PHP

Alex picture Alex · Feb 27, 2010 · Viewed 27.3k times · Source

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?

Answer

Doug T. picture Doug T. · Feb 27, 2010

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.