Never emit contents of any variable to the browser without treating it with htmlspecialchars() (or equivalent) first.
If you want your users to post formatted content either don't use html for formatting (use something like markdown) or parse the html to tree, and run it through whitelist filter that will let through only tags you want to pass, only attribute values that you want to pass, and only values of attribute that you want to pass (defined by narrow regexps that dont allow such thing as background:url(javascript:)).
To sum up never mix other data types with html (kept in static places like template files or read-only database tables), unless you are absolutely sure that they contain html you want to display, either by htmlspecialchars-ing them (safe and fast general policy) or by parsing and whitelisting (for cases that you really, really have to allow some html).