How Do I Retain Output Indentation?
I have some PHP code like the following (simplified):
<ul>
<?php
for ($Index = 1; $Index <= 10; $Index++)
{
echo("<li>" . $Index . "</li>\n");
}
?>
</ul>
The problem is that for all lines after the first, the output is without indentation. I want to keep my code neat, so I'd like all the <li>
elements to be aligned properly.
I tried outputting tabs before each element with \t
, but then the first line is indented more than intended. Outputting the tab after the element means the trailing </ul>
's placement will be messed up.
\r
does not work at all.
Are there any tricks to keeping output properly formatted, or do I have to live with messy code?
The first line is more indented than you want it to be because of the extra whitespace at the beginning of this line:
<?php
Since that white space is outside the PHP tags, it is output directly. But because it is outside the PHP tags, it is not included in the loop, and will only affect the first line.
You could do this to help avoid it:
<ul>
<?php
for ($Index = 1; $Index <= 10; $Index++) {
echo "\n <li>$Index</li>";
}
?>
</ul>
...and align the <?php ?>
tags at the beginning of the lines, or you could do this:
<ul><?php for ($Index = 1; $Index <= 10; $Index++) { ?>
<li><?php echo $Index; ?></li>
<?php } ?></ul>
...but as ridiculous as it seems, this:
<ul><?php for ($Index = 1; $Index <= 10; $Index++) echo "\n <li>$Index</li>"; ?>
</ul>
...is probably the best way to acheive what you are talking about leaving the least room for ambiguity (different PHP versions seem to handle this slightly differently - for instance in PHP 4.3.10 at least, there is an implicit line break after a ?>
tag which does not exist in PHP 5 (I think this may have been a bug). That is one of the reasons I don't use mixed HTML and PHP (although I know many people disagree with me on this point) but what I would rather do is this:
<?php
$out = "<ul>\n";
for ($Index = 1; $Index <= 10; $Index++) $out .= " <li>$Index</li>\n";
$out .= "</ul>";
echo $out;
?>
Use spaces. " " * 8, 16, 20, etc...
Or still use \t
in your php, then at the very end echo it all out after replacing \t
with spaces ,
echo preg_replace('/^\t/', '4_SPACES_HERE', $output_html);
精彩评论