View RSS Feed

John

Tidy up your HTML

Rate this Entry
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:

Code:
echo "<table>&nbsp;&nbsp;&nbsp; <tbody><tr>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <td>Hello World</td>&nbsp;&nbsp;&nbsp; </tr></tbody></table>"
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=php]echo "\r\n\t\r\n\t\t\r\n\t\r\n
Hello World
";[/code]
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; 

Submit "Tidy up your HTML" to Digg Submit "Tidy up your HTML" to del.icio.us Submit "Tidy up your HTML" to StumbleUpon Submit "Tidy up your HTML" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments

  1. Jordan's Avatar
    I believe I read something similar to this once in the user contributions on php.net but they were using DOM. I've never really cared if the HTML source code looked proper in a "view source" window though. Being obfuscated, such as it would appear all on one line, may be a good thing since it may thwart people (or at least annoy :)) people stealing your HTML.
  2. amrosama's Avatar
    interesting new technique
    thnx