PHP: Difference between htmlspecialchars() and htmlentities() Functions

2 functions exist in PHP to convert special characters to HTML entities (a kind of representations defined as in XML for web client such as browsers to recognize and render as special characters such as a spade: â™ , which can be represented as ♠ in HTML), namely htmlspecialchars() and htmlentities().

But what’s the difference?

The obvious part is htmlspecialchars() only convert 5 special characters that happen to be HTML specific:

  1. &‘ (ampersand) becomes ‘&’
  2. "‘ (double quote) becomes ‘"’ when ENT_NOQUOTES is not set.
  3. ‘ (single quote) becomes ‘'’ only when ENT_QUOTES is set.
  4. <‘ (less than) becomes ‘&lt;’
  5. >‘ (greater than) becomes ‘&gt;’

As you can recognize, all the 5 special characters are HTML reserved ones, so htmlspecialchars() is mostly used at preventing user web client from treating these characters as part of HTML constructs.

On the other hand, htmlentites() tries its best to convert all applicable characters to HTML entity representations including the 5 HTML specific language constructs.

Scroll to Top