Although encoding data for transferring back and forth between a HTML form, databases, and so on is extremely useful, PHP also supports a few more simple (and very convenient) conversions. For instance, for argument's sake, assume you would like to display the following text in the browser:
<A href="example.php">This is an example HTML Tag</A>
Now, the trick here is to get this string to display to the client browser as it is seen in the example (not as a hyperlink). For purposes such as this, when displaying characters that usually hold a significance in HTML, there are HTML entities. These entities are special strings interpreted by the browser and rendered as a character. For instance, < is the entity representation of the < character.
So, to display the preceding HTML code as text and have it not interpreted by the browser, it would have to resemble something like the following:
<A href="example.php">This is an example HTML Tag</A>
Although it's not much different from URL encoding, attempting to manually convert these HTML entities soon becomes quite an annoying task. Luckily, PHP provides two functions to automate this conversion.
The first of these functions is htmlentities(). This function converts all applicable characters into their corresponding HTML entities. The syntax of this function is as follows:
$string represents the string to convert, $quote_style is a flag determining how to treat quote characters (single and double), and $char_set is a string representing the character set to use in the conversion. The possible flags for the $quote_style parameter are shown in .
Table 5.1. htmlentities() Quote Style Flags
ENT_COMPAT
Convert only double-quote characters (default).
ENT_QUOTES
Convert both single and double-quote characters.
ENT_NOQUOTES
Leave all quote characters as is.
When executed, the htmlentities() function will convert and return the characters represented in $string to their respective HTML entities (if available). For instance, when the following code snippet is executed:
<A href='foo'>"Jack & Jill"</A>
Although effective, at times it may not be necessary to convert every possible character that has an HTML entity equivalent into entity form. Usually, there are a few select characters that need to be converted for the text not to be rendered by the browser as HTML code. For these cases, PHP also provides a watered-down version of the htmlentities() function, which converts only these characters: &, ", ', <, and >. This function is called htmlspecialchars() and has the following syntax: