Page 1 of 1

Outputting HTML Rate Topic: -----

#1 andrewsw  Icon User is online

  • Speak up, I'm wearing a towel
  • member icon

Reputation: 5219
  • View blog
  • Posts: 20,186
  • Joined: 12-December 12

Post icon  Posted 31 October 2015 - 04:51 AM

The purpose of this tutorial is to demonstrate the various ways to output HTML from PHP, but also to:

  • Move away from multiple echo statements
  • Move away from excessive use of dots . to concatenate (join) text, by
  • Knowing how to embed variables in strings
  • Introduce HEREDOC syntax
  • The sprintf() function
  • Introduce the idea of code separation

Here's a typical example:
<?php
$css = 'main.css';
$title = 'Output HTML';

echo '<!DOCTYPE html>';
echo '<html>';
echo '    <head>'; 
echo '        <link rel="stylesheet" type="text/css" href="' . $css . '">';
echo '        <title>' . $title . '</title>';
echo '   </head>';
echo '   <body>';
?>


We don't need dots to include the variables, we can embed variables within strings. This does require switching to double quotes as single quotes won't interpret, interpolate, variables.
<?php
echo '<!DOCTYPE html>';
echo '<html>';
echo '    <head>'; 
echo "        <link rel='stylesheet' type='text/css' href='{$css}'>";
echo "        <title>{$title}</title>";
echo '   </head>';
echo '   <body>';
?>


The braces { } around the variable are not essential, although they can be depending on the character that immediately precedes or follows the variable. I always include them, it is clearer in my opinion, and less error prone.

We cannot directly put a double quote inside a double-quoted string, so I switched to single quotes.

It is possible to embed double quotes but they need to be escaped using \"
echo "        <link rel=\"stylesheet\" type=\"text/css\" href=\"{$css}\">";


We would need to do the same for single quotes \' inside a single-quoted string. Examples further down show how we can avoid having to escape quotes.

We need braces when embedding array elements {$names['bob']}. (It may work without the braces but I encourage you to ignore this and always include them.)

When embedding an array element we can omit the single quotes around the key:
$names = array("bob" => "Robert");
echo "Hello to {$names[bob]}.";


With multi-dimensional arrays though, omitting the single quotes generates a warning, so I would reinstate them.

Complex (curly) syntax :the docs

It is possible to avoid repeated echo statements by breaking out of PHP into HTML:
?>
<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' type='text/css' href='<?php echo $css; ?>'>
        <title><?php echo $title; ?></title>
   </head>
   <body>
<?php


Initially this looks neater, although the embedded echoes are clumsy. The problem with this is not the code itself, but that switching between PHP and HTML violates our longer term aim of achieving code separation. Our aim should be to achieve clear separation between our HTML, PHP, CSS and JS. Separation of concerns.



If you are writing pure HTML - that is, without embedded variables - then you can include this fragment by writing it to a file and using include('header.html');. You can then insert the same fragment wherever you need it.

Even though the file is pure HTML you can give it a .php extension, or perhaps use something like .html.php.



One approach to removing the repeated echo statements is to use a single echo statement, across multiple lines:
<?php
echo "<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' type='text/css' href='{$css}'>
        <title>{$title}</title>
   </head>
   <body>";
?>


This is an improvement, and easier to read. With a large HTML block though, it becomes harder to recognise that it is a single, quoted, statement, and easier to fail to match, and synchronise, quotes.

Instead, it requires a small change to use a HEREDOC string, which is intended to work with multiple lines, doesn't require surrounding quotes, and allows any combinations of (unescaped) single and double quotes.
<?php
echo <<< EOT
<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' type='text/css' href='{$css}'>
        <title>{$title}</title>
   </head>
   <body>
EOT;
?>


The arrows <<< (an operator) introduce the HEREDOC. The word EOT delimits this string. This is a word that I made up (end of text). It can be any (reasonable) word and is traditionally capitalized.

Note that EOT is the last word on the first line, then there is a newline. The closing EOT must occur on the far left and be immediately followed by a semi-colon.

I will highlight again that we can include all kinds of quotes in the HEREDOC without having to escape them.

I prefer to take this a step further and assign the HEREDOC to a variable, even if I just immediately echo it.
<?php
$top = <<< EOT
<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' type='text/css' href='{$css}'>
        <title>{$title}</title>
   </head>
   <body>
EOT;

echo $top;
?>


The use of a variable will eventually aid in our ambitions towards code separation, as well as offering more flexibility.

The variables used in the HEREDOC need to exist before the statement is encountered. For additional flexibility, and logic, we can use str_replace() and other functions to modify the HEREDOC variable. Here is an example where $navbar is the HEREDOC:
<?php
// Determine whether to show a link for login or logout.php.
if ($logged_in) {
    $navbar = str_replace("login.php", "logout.php", $navbar);
    $navbar = str_replace("Log In", "Log Out: {$username}", $navbar);
    $navbar = str_replace("inactive", "active", $navbar);
}

// Use an id to disable the current-page's link.
$navbar = str_replace("\"$thispage\"", "\"#\" id=\"current\"", $navbar);
?>


Something that could be considered is to invent your own pattern for delimiting and naming variable content within HEREDOCs, e.g. <<name>>, so that you can more easily identify and modify this content later.

An important function for producing formatted strings is sprintf(). We can combine its use with HEREDOCs:
<?php
$top = <<< EOT
<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' type='text/css' href='%s'>
        <title>%s</title>
   </head>
   <body>
EOT;

echo sprintf($top, $css, $title);
?>


Using sprintf() with HEREDOCs is very flexible. Variables don't need to exist beforehand as %s, etc., are ignored in the HEREDOC; they only having meaning when used with sprintf() and, at that point, different variables can be substituted.

printf() is the same function (has the same features) except that it outputs directly. That is, echo sprintf() is the same as printf(). vsprintf() accepts an array of values.

Study the docs and its examples as there is a lot more to sprintf than just inserting variables, particularly in terms of formatting numbers.



My main aim has been to demonstrate different ways to output HTML. A secondary aim is to encourage the separation of HTML from PHP. Includes, HEREDOCs and variable substitution are tools that assist in this process. See here for more information.

This post has been edited by andrewsw: 31 October 2015 - 06:57 AM


Is This A Good Question/Topic? 2
  • +

Replies To: Outputting HTML

#2 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3415
  • View blog
  • Posts: 12,127
  • Joined: 08-August 08

Posted 02 November 2015 - 08:08 AM

I'd add that using file_get_contents() is a good way to completely separate your HTML from your PHP code. When they're in separate files the indenting in the HTML file only applies to it, and same goes for the PHP file. There's also a lot less to read through in either file, so if you know an issue is in one and not the other, debugging becomes a much smaller problem.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1