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.
You should also read:
- How to display HTML code on a web page?
- jQuery: Selecting elements with uncommon / special characters in ID or class name
- Turn off and disable magic_quotes_gpc in .htaccess
- PHP: Escape String Literals for SQL, mysqli::real_escape_string and PDO to Prevent SQL Injection Attacks
- MySQL: Find non-ASCII characters in a table column


Facebook
Twitter
Google Plus