Difference between htmlspecialchars_decode and html_entity_decode

There are quite a few similar functions in PHP. Some of them are almost identical like echo and print and some have subtle differences which are not obvious at the first glance. We can put htmlspecialchars_decode and html_entity_decode in this category. There is a lot of confusion between notions of HTML special characters and HTML entities so let’s look into the difference.

A detailed look into the documentation reveals that the notion of special characters is used when referring characters which have special significance in HTML markup. For example, characters less than (<) and greater than (>) are used in HTML markup (for example, <br /> is used as a line break). Usually, modern browsers are smart enough to distinguish those characters if they appear in the text from those used for the markup. But it’s always better to be on a safe side and to encode the special characters. Function htmlspecialchars_decode is opposite of the htmlspecialchars which are the one used to convert HTML special characters to entities. Special characters that are encoded are < (less than – becomes &lt;), > (greater than – becomes &gt;), “ (double quote – becomes &quot;), ‘ (single quote – becomes &#039;), & (ampersand – becomes &amp;).

When you convert HTML special characters those become HMTL entities. However, there are much more HMTL entities than those which are a representation of the HMTL reserved characters. So function htmlentities will convert all characters which have HTML character entity equivalents into these entities, like many mathematical, technical, and currency symbols. Function html_entities_decode is the opposite of the previously mentioned function and basically converts back entities into the characters.

Function htmlentities is better if you are expecting the use of charsets which may contain different special characters or symbols. On the other side, htmlspecialchars won’t try to translate anything except HTML reserved characters so it won’t plague your text with entities for “everything” which can be an issue at a later time.

Leave a Reply

Your email address will not be published. Required fields are marked *