Question

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";
Was it helpful?

Solution

There are a few ways to echo HTML in PHP.

1. In between PHP tags

<?php if(condition){ ?>
     <!-- HTML here -->
<?php } ?>

2. In an echo

if(condition){
     echo "HTML here";
}

With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:

echo '<input type="text">';

Or you can escape them like so:

echo "<input type=\"text\">";

3. Heredocs

4. Nowdocs (as of PHP 5.3.0)

Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).

There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).

The primary benefit of using a template engine is keeping the design (Presentation Logic) separate from the coding (Business Logic). It also makes the code cleaner and easier to maintain in the long run.

If you have any more questions feel free to leave a comment. Further reading is available on these things in the PHP Documentation.

God Bless!


NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.

OTHER TIPS

try like this:

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

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

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 is a bit of a pain to write */ ?>
<?php else: ?>
    <!-- else -->
<?php endif; ?>

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.

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.

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, then write the html, then put the php output back into the page.

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

<?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 May Help You.......

<?php
echo <<<HTML

your html tags here

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

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

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.

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 print function to echo text in PHP file as follow

<?php

  print('

    <div class="wrap">

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

    </div>


  ')

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

or

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

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 } ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top