[php] How can I echo HTML in PHP?

I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?

echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";

This question is related to php html templates echo

The answer is


This is how I do it:

<?php if($contition == true){ ?>
         <input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
         <p>No input here </p>
<?php } ?>

$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';

echo('Echo as HTML' . htmlspecialchars((string)$enter_string));

I am partial to this style:

  <html>
    <head>
<%    if (X)
      {
%>      <title>Definitely X</title>
<%    }
      else
      {
%>      <title>Totally not X</title>
<%    }
%>  </head>
  </html>

I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.


In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.

For example you want to display the images of a gallery:

foreach($images as $image)
{
    echo
    '<li>',
        '<a href="', site_url(), 'images/', $image['name'], '">',
            '<img ',
                'class="image" ',
                'title="', $image['title'], '" ',
                'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
                'alt="', $image['description'], '"',
            '>',
        '</a>',
    '</li>';
}

Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.


You could use the alternative syntax alternative syntax for control structures and break out of PHP:

<?php if ($something): ?>
    <some /> <tags /> <etc />
    <?=$shortButControversialWayOfPrintingAVariable ?>
    <?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
    <!-- else -->
<?php endif; ?>

Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)

$page = 'Hello, World!';
$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.

It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)

I.e.:

<?php
    ob_start();
    echo('Hello, World!');
    $php_output = ob_get_contents();
    ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
    echo($php_output);
?>
<hr>
Template footer

Try this:

<?php
    echo <<<HTML

    Your HTML tags here

HTML;
?>

echo '
<html>
<body>
</body>
</html>
';

or

echo "<html>\n<body>\n</body>\n</html>\n";

Try it like this (heredoc syntax):

$variable = <<<XYZ
<html>
<body>

</body>
</html>
XYZ;
echo $variable;

Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.

The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.

I prefer this compact style:

<?php
    /* do your processing here */
?>

<html>
<head>
    <title><?=$title?></title>
</head>
<body>
    <?php foreach ( $something as $item ) : ?>
        <p><?=$item?></p>
    <?php endforeach; ?>
</body>
</html>

Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.


Don't echo out HTML.

If you want to use

<?php echo "<h1>  $title; </h1>"; ?>

you should be doing this:

<h1><?= $title;?></h1>

Simply use the print function to echo text in the PHP file as follows:

<?php

  print('
    <div class="wrap">

      <span class="textClass">TESTING</span>

    </div>
  ')
?>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to templates

*ngIf else if in template 'if' statement in jinja2 template How to create a link to another PHP page Flask raises TemplateNotFound error even though template file exists Application not picking up .css file (flask/python) Django: How can I call a view function from template? Angularjs Template Default Value if Binding Null / Undefined (With Filter) HTML email in outlook table width issue - content is wider than the specified table width How to redirect on another page and pass parameter in url from table? How to check for the type of a template parameter?

Examples related to echo

Multi-line string with extra space (preserved indentation) Bash: Echoing a echo command with a variable in bash Echo a blank (empty) line to the console from a Windows batch file Add php variable inside echo statement as href link address? How to format font style and color in echo How do I make a Windows batch script completely silent? Is there a php echo/print equivalent in javascript How to use css style in php How can I align the columns of tables in Bash? Double quotes within php script echo