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:
- ‘&‘ (ampersand) becomes ‘&’
- ‘"‘ (double quote) becomes ‘"’ when ENT_NOQUOTES is not set.
- ‘‘‘ (single quote) becomes ‘'’ only when ENT_QUOTES is set.
- ‘<‘ (less than) becomes ‘<’
- ‘>‘ (greater than) becomes ‘>’
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.