One of the approaches I have taken is to pipe the html input through HTML Tidy (can be found under HTML at the w3c.org site.) This can be useful in an application or at least while debugging your application to avoid just the problem you ran into. Craig Johnson