139

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";
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607
  • 3
    \n doesn't work in html. I guess you meant echo "
    ";
    – Weishi Z Oct 13 '14 at 05:34
  • Good pracitice say to separete your logic from view (like in MVC). use templetig engine like Twig to separete your view from script logic - http://twig.sensiolabs.org/ Insted of implementing your html markup to your php script do it other way round. Implement php variables to twig temple. As soon as you get what I mean you will see benefits of this aproach. Twig solve this kind of issues. For small chank of code you can write your own twig extension which you can then use with in secounds to performe some complicated but repetative tasks. – DevWL Jan 09 '17 at 02:43

13 Answers13

300

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.


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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Bier
  • 14,183
  • 17
  • 67
  • 103
  • 8
    Shouldn't the "/* HTML here */" REALLY be a "" ? ;) – Jeremy Logan Jul 08 '09 at 20:50
  • 1
    Yes on the first post you are correct. I was caught up in the code haha. Thank you. – Chris Bier Jul 08 '09 at 21:00
  • 1
    Thanks, @Chris B. it helped me. With echos, if you wish to use double quotes in your HTML you must use single quote echos like so: I was actually missing this. – Ayush Mishra Jan 02 '13 at 09:13
  • 1
    Actually, the only short tags available from 5.4 onwards are the short echo tags `=$var?>`. Short tags are discouraged as usual, and are to be removed (` doStuff() ?>`). – igorsantos07 Oct 11 '15 at 17:26
  • 1
    And, if you're looking for a way to print out something in the code from within a controller file (in MVC working), like I did and got me here, then you need to use "var_dump(myvar)" instead of "echo myvar". – TheCuBeMan Oct 14 '15 at 14:07
  • Could somebody expand the Heredocs section of this answer pls. – Caltor Jan 06 '17 at 01:14
  • 1
    I will try to update it soon. In the meantime, you can look at the PHP docs for more info on the heredoc syntax: http://www.php.net/manual/en/language.types.string.php – Chris Bier Jan 24 '17 at 21:19
70

Try it like this (heredoc syntax):

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

</body>
</html>
XYZ;
echo $variable;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lfx
  • 1,353
  • 13
  • 23
  • 8
    @MhdSyrwan just random chars, you can read more here http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc – lfx Sep 23 '11 at 18:22
  • 2
    care to elaborate? I don't see the opening or closing PHP brackets, but both HTML and PHP, so huh? - the link works and answers it better, but maybe it should be in the answer text then, not in the comments? – Julix May 14 '17 at 20:06
  • @Julix of course you need to add opening and ([depends](http://www.php-fig.org/psr/psr-2/#22-files)) closing PHP tags. He just wanted to make the example short. – Fahmi Jan 10 '18 at 10:07
  • I got it; somehow I missed this was heredocs syntax (i.e. the entire code is php). I got confused, since I was new to PHP at the time and used to seeing syntax like ` ` --- So I thought a bunch of brackets were missing and was unsure where exactly they'd go. It's always funny when my slightly older comments get answered, since I was so very new to it all then. – Julix Jan 11 '18 at 18:50
33

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; ?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
  • @Jeremy: This is probably the best, most direct way assuming you are not looking for something more... Are you looking for something more? – Frank V Jul 08 '09 at 20:30
  • 1
    Yes, specifically the ability to use PHP comments in between the HTML, comments that will not be echo'd. – Robin Rodricks Jul 08 '09 at 20:33
16

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.

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
7

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
7

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
julz
  • 3,369
  • 2
  • 17
  • 8
4
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';

echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

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>
  ')
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Code Spy
  • 9,626
  • 4
  • 66
  • 46
1

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.

Community
  • 1
  • 1
totymedli
  • 29,531
  • 22
  • 131
  • 165
1
echo '
<html>
<body>
</body>
</html>
';

or

echo "<html>\n<body>\n</body>\n</html>\n";
Alessandro
  • 900
  • 12
  • 23
0

Try this:

<?php
    echo <<<HTML

    Your HTML tags here

HTML;
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Edwin Thomas
  • 1,186
  • 2
  • 18
  • 31
0

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 } ?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • I agree. It could be that `($contition == true)` is frowned upon. Preferrably, you would instead do `($contition)`(sic) – RockyK Feb 05 '21 at 20:27
  • @AFriend it could be that, as you point out, the same answer was posted a decade before this one, and was accepted by the OP, and this adds nothing to it. – miken32 May 31 '21 at 23:39
-2

Don't echo out HTML.

If you want to use

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

you should be doing this:

<h1><?= $title;?></h1>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hmache
  • 140
  • 1
  • 6