Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of outputting a large block of HTML in PHP

Tags:

php

I am learning PHP (no programming experience) from a book. The examples in the book use a strange way of outputting a large block of HTML conditionally. It closes the PHP tag inside the conditional, and reopens it after outputting the HTML. I understand (after some head scratching) how it works, but it seems like a dodgy, not-intended-to-be-used-like-this, workaround.

<?php
    if(something == somethingelse) {
        echo "some message";
    }
     else {
?>
<big-block-of-html>
</big-block-of-html>
<?php }
?>

The book did introduce the heredoc syntax, but never used it. Is there a right way of doing this? It would seem more intuitive to output the HTML from within PHP.

like image 743
ntc Avatar asked Nov 25 '10 12:11

ntc


People also ask

How do I code HTML in PHP?

Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text editor in which we want to use the PHP. Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the code of PHP. And, then we have to type the start and end tag of PHP.

Can you echo HTML in PHP?

Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.

Which is the correct way to start a multiple line PHP comment?

PHP multi-line line comment begins with /* , and ends with */ .

What is the correct syntax for a PHP opening tag?

The <= tag is called short open tag in PHP. To use the short tags, one must have to enable it from settings in the PHP. ini file. First of all ensure that short tags are not disabled, To check it, go into php.


1 Answers

That's exactly how PHP is supposed to be used and is much more readable, elegant and robust than all alternatives*. I'd just go for a better indented style:

<?php
    // normal
    // code
    // here
?>
<?php if ($foo) : ?>

    <div>
        <!-- more HTML -->
    </div>

<?php endif; ?>

* Unless you go for completely code-free templates like Smarty of course...

like image 146
deceze Avatar answered Oct 06 '22 18:10

deceze