tags:

views:

61

answers:

3

i know exactly the difference between the two functions. what i want to know is what would be the possible reasons to use htmlspecialchars() when you have a more complete option, that is htmlentities(). thank you (:

+4  A: 

Because:

  • Sometimes you're writing XML data, and you can't use HTML entities in a XML file.
  • 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.

Artefacto
thanx. this is objective and useful info (:
hugo_leonardo
A: 

htmlspecialchars () does the minimum amount of encoding to ensure that your string is not parsed as HTML. This leaves your string more human-readable than it would be if you used htmlentities () to encode absolutely everything that has an encoding.

grossvogel
+2  A: 

htmlspecialchars may be used when there is no need to encode all characters which have their HTML equivalents.

For example, 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>.');
// Outputs: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.

echo htmlspecialchars('<Il était une fois un être>.');
// Outputs: &lt;Il était une fois un être&gt;.

The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.

Last but not least, the htmlspecialchars can be used when the data will be processed not only through a browser (to avoid decoding HTML entities), or, like said in an other answer, if the output is XML.

MainMa