What is the best way to format long HTML strings in PHP?

I know this is a really subjective question, but for best practices (and readability) I don't seem to be able to fix the best way to format long HTML strings. I usually do it like this:

echo ' <div> <p>Content Inside</p> <div class="subbox"> <ul> <li>etc.</li> <li>etc.</li> <li>etc.</li> <li>etc.</li> </ul> </div> </div> '; 

But I still don't like the result, especially if it appears in the middle of a large block of code. This is just messy.

+4
source share
6 answers

You can jump out of PHP and directly enter HTML:

 <?php $var = "foo"; ?> <div> <ul> <li>Foo</li> </ul> </div> <?php $foo = "var"; ?> 

If all you do is echo / print, I think it is a lot cleaner. In addition, you do not need to run and avoid single / double quotes inside the HTML itself.

If you need to save HTML in a variable, you can use HEREDOC :

 $str = <<<EOD <div> <ul> <li>Foo</li> </ul> </div> EOD; 
+9
source

Why not just embed your PHP in HTML? This is how PHP was originally designed to work.

 // PHP goes here ?> <div> <p>Content Inside</p> <div class="subbox"> <ul> <li>etc.</li> <li>etc.</li> <li>etc.</li> <li>etc.</li> </ul> </div> </div> <?php // More PHP here 
+3
source

The old Perl-style heredoc school also works:

 echo <<<EOL <div> <p>Content Inside</p> <div class="subbox"> <ul> <li>etc.</li> <li>etc.</li> <li>etc.</li> <li>etc.</li> </ul> </div> </div> EOL; 

Using multiple <?php ?> Blocks is cleaner, but if you are in a class definition or something else, heredoc may be less inconvenient (although printing HTML from a class definition is nothing but a nuisance).

+3
source

I would do it like this:

 echo '<div> <p>Content Inside</p> <div class="subbox"> <ul> <li>etc.</li> <li>etc.</li> <li>etc.</li> <li>etc.</li> </ul> </div> </div>'; 
+2
source

I prefer an MVC architecture such as Code Igniter to separate the view from the logic. Basically, all of your templates are stored separately, and you use the alternative PHP syntax structures described here to format your HTML.

+2
source

The best way is to use a template system where you can separate your logic from a presentation. In the template, you only have things like:

 <html> <body> <h1><?php echo $title; ?></h1> <p><?php echo $myparagraph; ?></p> </body> </html> 
+1
source

Source: https://habr.com/ru/post/1304576/


All Articles