What is the best way to echo results from the database into html code in PHP?

后端 未结 5 2025
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 05:04

when I have a value like this in the database (\"foo\")

how can I echo it without any conflict with html code

notice



        
5条回答
  •  悲&欢浪女
    2021-01-15 05:26

    htmlspecialchars() basically, for example

    
    

    The ENT_QUOTES is optional and also encodes the single quote ' .

    I used $value since I'm not sure what exactly you have in the database (with or without quotes?) but it will sit in some kind of variable if you want to use it anyway, so, I called that $value.

    Since the above is a bit unwieldy I made a wrapper for it:

    // htmlents($string)
    function htmlents($string) {
      return htmlspecialchars($string, ENT_QUOTES);
    }
    

    So you can

    
    

    Not to be confused with the existing htmlentities(), which encodes all non-standard characters. htmlspecialchars() only encodes &, <, >, " and ', which is more appropriate for UTF8 pages (all your webpages are UTF8, right? ;-).

提交回复
热议问题