htmlentities() vs. htmlspecialchars()
What are the differences between htmlspecialchars()
and htmlentities()
. When should I use one or the other?
From the PHP documentation for htmlentities:
This function is identical to htmlspecialchars()
in all ways, except with htmlentities()
, all characters which have HTML character entity equivalents are translated into these entities.
From the PHP documentation for htmlspecialchars:
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities()
instead.
The difference is what gets encoded. The choices are everything (entities) or everything minus "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use htmlspecialchars
whenever possible.
htmlspecialchars
may be used:
When there is no need to encode all characters which have their HTML equivalents.
If you know that the page encoding match the text special symbols, why would you use htmlentities
? htmlspecialchars
is much straightforward, and produce less code to send to the client.
For example:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.
When the data will be processed not only through a browser (to avoid decoding HTML entities),
If the output is XML (see the answer by Artefacto).
Because:
htmlentities
substitutes more characters than htmlspecialchars
. This is unnecessary, makes the PHP script less efficient and the resulting HTML code less readable. htmlentities
is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8 and you're handling data with an encoding different from the page's.
上一篇: VARIABLE在PHP中?