htmlentities() vs. htmlspecialchars()

前端 未结 12 2004
走了就别回头了
走了就别回头了 2020-11-22 02:50

What are the differences between htmlspecialchars() and htmlentities(). When should I use one or the other?

12条回答
  •  不知归路
    2020-11-22 03:10

    htmlspecialchars may be used:

    1. 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('.');
      // Output: <Il était une fois un être>.
      //                ^^^^^^^^                 ^^^^^^^
      
      echo htmlspecialchars('.');
      // 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.

    2. When the data will be processed not only through a browser (to avoid decoding HTML entities),

    3. If the output is XML (see the answer by Artefacto).

提交回复
热议问题