CGI:😛retty equivalent in PHP, or, how to tidy my HTML?
I write statements like this all the time:
<?php
print "<p>Here's a list of items:<ul>";
$items = array("item1", "item2", "item3");
foreach ($items as $item) {
print "<li>$item</li>";
}
print "</ul>";
?>
This writes perfectly valid HTML, but it all writes it to one line.
People say I should use "\n" and "\t" throughout my code if I want it
to split it up over different lines or to indent the inner elements.
That's a big hassle. In Perl, the CGI module has an extension called
CGI:😛retty, which will format the outgoing HTML source code into
something that's much easier to read. So, instead of getting back:
<p>Here's a lit of items:<ul><li>item1</li><li>item2</li>
<li>item3</li></ul>
I would get code back that looked more like this:
<p>Here's a lit of items:
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
And I didn't have to add a bunch of obfuscating "\n" and "\t"
characters! Anyway, I can't believe that perl would have a feature
like this, but not PHP.
I thought about how I could write it myself, using ob_start() and some
regular expressions, but before I start on that path, I wanted to ask
if a package like this already exists.
This comment in the php manual seemed pretty clever:
http://us3.php.net/ref.outcontrol
A cool way to use this is to run the output through HTML-tidy and get
really nicelooking output without having to manually add indenting
etc. Try this at the end (after doing an ob_start before outputting
anything).
<?php
$str=addslashes(ob_get_contents());
$fp=popen("echo \"" . $str . "\" | /usr/bin/tidy -i -u -q -latin1 --indent-spaces 1 -wrap 0", "r");
@$newstr=fread($fp, 99999);
ob_end_clean();
Header( "Content-length: " . strlen( $newstr ) );
echo $newstr;
?>