PHP htmlentities() – convert characters to html entities

PHP htmlentities function is used for covert the characters to its HTML entities. This function will automatically identify the characters which have an equivalent HTML entity , and then convert to it.

Its Synatx will be ;
htmlentities ( string , quote style , Character set );

First parametrer will be the string to convert
Second parameter is optional. Here we can specify how to deal with single quotes (‘) and double quotes (“)
Available quote styles are

  • ENT_COMPAT : Will convert double-quotes and leave single-quotes alone.
  • ENT_QUOTES : Will convert both double and single quotes.
  • ENT_NOQUOTES : Will leave both double and single quotes unconverted.

Third parameter is also optional , which defines the character set used in conversion. By default character set will be ISO-8859-1

Now look at some sample PHP programs using htmlentities function

$data="mysqlbrain's tutorials are very <b>good<b>";
echo htmlentities($data);
echo "<br>";
echo htmlentities($data,ENT_QUOTES)

Now look at the source code of the ouput in browser , it will be

mysqlbrain’s tutorials are very <b>good<b>
mysqlbrain’s tutorials are very <b>good<b>

We can see that first htmlentities statement leaves the single quote , and second time it covert the single quote to html entity.

Its a good practise to use this function before storing the data to mysql tables. And we can use PHP html_entity_decode function to decode the string.