Quick ‘n Dirty: htmlspecialchars vs. htmlentities

When building HTML with PHP, it’s pretty common to need to emit the value of a PHP variable as an attribute value of an HTML tag. Just spitting out the variable directly will break the HTML if the value has a quote in it. There’s two functions in PHP that can take care of this: htmlspecialchars and htmlentities. Here’s a reasonable rule of thumb for which to use (stolen shamelessly from the comments on the PHP site for htmlspecialchars – I’m writing it up here because I’m too lazy to keep looking it up on the PHP site).

Use htmlspecialchars for attribute values, htmlentities for everything else.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>