PHP - Tidy extension

From LXF Wiki

Practical PHP

(Original version written by Paul Hudson for LXF issue 64.)


Tidying up after yourself is easier than you thought...


The Tidy PHP extension is one of the least understood out there, despite its name giving away what it does. Part of the problem is that it was being written alongside development of PHP 5, and so saw substantial revision before it was finalised - if you used an early version of Tidy, you can be guaranteed you need to relearn it now.

Another part of the problem is that few people see any need for Tidy at all: it smartens up the HTML output of your PHP scripts - it pretty-prints it. Consider this piece of PHP code:

<?php 
$monkeys = array('Minky','Manky','Stinky','Woopsy','Fuzzy','Scuzzy','Bubbles'); // define monkey array
$num_monkeys = count($monkeys);	// count names in array		 
for ($i = 0; $i < $num_monkeys;  $i++) echo $monkeys[$i]. "<br />"; // loop names
?>

This functioning code fragment loops through an array holding the names of monkeys, printing out the names separated by HTML line breaks. While this might display just fine on-screen, anyone who clicks "View Source" in their browser will see a mess:

Minky<br />Manky<br />Stinky<br />Woopsy<br />Fuzzy<br />Scuzzy<br />Bubbles

By comparison, the use of tidy on the above code gives the following result:

 Minky<br />
 Manky<br />
 Stinky<br />
 Woopsy<br />
 Fuzzy<br />
 Scuzzy<br />
 Bubbles<br />

So, the names are separated by HTML line breaks that look fine sent through a web browser, but they don't actually have any textual lines break to make source code reading easier. "Aha!" you say, "I didn't want those dirty pirates stealing my code anyway!" Perhaps. However, this is an Open Source world: I've learnt a huge amount about HTML (probably more than is safe for any one person to know) by examining the code of others, and I think it's important to help others learn, too. Sure, they /could/ decipher our HTML if they were sufficiently talented, but a little help from Tidy will make their lives much easier, while makes us look like benevolent code geniuses. Everyone's a winner!