Tidy is a HTML clean and repair tool. You may use Tidy to fix bad markup. Tidy can also be to automatically clean up html output generated by PHP. Cleaner and valid HTML means your page will be consistent in a wide variety to of browsers.
Now, we talk how to activate Tidy extension.
Tidy: Activation PHP tidy Extension in php.ini
Now, we try to activate this extension.
Open your php.ini. Usually within c:\wamp\bin\php\php5.3.5 or c:\xampp\php\php.ini (depend on your php installation). Uncomment at line extension=php_tidy.dll.
Restart your apache. You can restart from services. If, you use windows XP, you can access from start > control panel > Performance and Maintenance > Administrative Tools > Services. Find apache, then click restart.
Our PHP Server ready for Tidy, Now write some bad HTML.
<htm> <h1> Test header<p> Test html document <br>
We intentionally didn’t close the HTML tag and p tag. The document definition is not there. So, its not a valid XHTML. Lets clean it out with Tidy.
$bad_html = '<htm> <h1> Test header<p> Test html document <br>'; $tidy = new tidy(); $tidy->parseString($bad_html); //parse html into tidy object $tidy->cleanRepair(); echo $tidy;
Save it to a file and run. You should see vaild html code in your browser source .
If you doubt it, check the output with this validator.
Well, code out put is clean and valid, but not much readable? You have to change one lines in the above code to pass an options array. The final code will look like this.
$bad_html = '<htm> <h1> Test header<p> Test html document <br>'; $tidy = new tidy(); $options = array("output-xhtml" => true, "indent" => true); //added option array $tidy->parseString($bad_html, $options); //pass options $tidy->cleanRepair(); echo $tidy;
Run. You will see indented, clean, valid XHTML. for test see your browser source again:
Notice that
is converted into
. Why? Setting output-xhtml option to true converts the HTML into XHTML. Its a really nice feature.
You have learnt quite a couple of things. How about writing a simple web-based code cleaner? Lets call it tidy web!
<?php if ( !empty($_POST['code']) ){ $bad_html = $_POST['code']; $tidy = new tidy(); $options = array("output-xhtml" => true, "indent" => true); //added option array $tidy->parseString($bad_html, $options); //pass options $tidy->cleanRepair(); $good_html = $tidy->html(); } ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Tidy Web</title> <style> form * { display: block; } </style> </head> <body> <form method='post'> <label> Paste HTML:</label> <textarea name='code' cols='100' rows='15'><?php echo isset($good_html) ? $good_html : ''; ?></textarea> <input type='submit' value='Clean' /> </form> </body> </html>
The page should look like the one below
You have just finished it! But, don’t stop here, check the tidy manual and experiment with other functions and options. Have fun!
Like to explore things, startups and new technologies. Web Developer, Traveler.