This is something that has always bothered me about PHP and I have never found an answer. Hopefully this example will provide enough information to understand my question, as I don't know how to explain it thoroughly in words.
Here is some PHP inside of HTML, in a .php file. This type of things occurs pretty often:
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<?php
foreach ($errors as $error)
{
?>
<li><?= $error ?></li>
<?php
}
?>
I have disregarded the end tags of the HTML and used <?=
shortcuts to avoid any unnecessary text.
Now, here is what expect in the HTML output (i.e., right-click -> view source):
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<li>Example Error</li>
However, here is the actual result:
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<li>Example Error</li>
Why? Because the foreach
loop from PHP is indented 3 tabs in, so the <li>
it is generating gets an ADDITIONAL 3 tabs. The solution I have been using? Here:
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<?php
foreach ($errors as $error)
{
?>
<li><?= $error ?></li>
<?php
}
?>
Sure, this works - but man is it ugly! It seems like I have two options: make my HTML output ugly and my code readable OR make my HTML readable and my code ugly. Why can't I have both? Is there no other way?
The best thing to do, I guess, is make the code readable and the output ugly. Who checks the source code anyway? I know this is probably the most popular reaction. Ugly HTML source code just bothers me, and I wish there was a way around it without sacrificing PHP code readability.