Tidy up your HTML
by
, 12-17-2008 at 09:00 PM (1188 Views)
If you are a php programmer, you should be aware of the annoyances brought upon by html. I am not saying html is annoying, but when you combine php and html in the same document, it becomes a head ach. Even if you separate your presentation logic from your business logic and data, your html source code will most likely look like crap. Sure you might spend a few minutes properly indenting your php source, but once that php executes and sends the response to the browser, at the very least, there will be issues with your indenting, that is, if your html is not on a single line. For example:Though the code may look properly indented. If you look at the source code once your browser renders it, it will all be on one line. Sure you can use the \t, \r, and \n characters, but but who really wants to do that?Code:echo "<table> <tbody><tr> <td>Hello World</td> </tr></tbody></table>";
[code=php]echo "\r\n\t
";[/code]\r\n\t\t \r\nHello World \r\n\t
Now if that does not look like crap, then I do not know what does. With PHP5 you can use the tidy functions available from PECL. Using this wonder function is easy. First you have to capture your html in an output buffer. Once you have the entire html contents in a string, use the tidy_parse_string function. There are several configuration options you can specify which can alter your html even further like making your document xhtml compliant. Here is what I use which will indent the html properly and make it xhtml compliant:Code:?ob_start();//html code here$output = ob_get_contents();ob_end_clean();$options = array("output-xhtml" => true, "indent" => true, "indent-spaces" => 4); $tidy = tidy_parse_string($output, $options);tidy_clean_repair($tidy);echo $output;










