PHP htmlspecialchars


PHP htmlspecialchars() function function converts some HTML special characters such as <, >, & and " into &lt;, &gt;, &amp; and &quot; etc. Note the string parameter inside htmlspecialchars function should be quoted using single quote ' but not double quote ".

<?PHP
$str='<table><tr><td>name<td>address</table>';
echo $str;  //<table><tr><td>name<td>address</table>
echo htmlspecialchars($str); 
//&lt;table&gt;&lt;tr&gt;&lt;td&gt;name&lt;td&gt;address&lt;/table&gt;
$str="<table><tr><td>name<td>address</table>";
echo htmlspecialchars($str);  //Not converted
//<table><tr><td>name<td>address</table>?>

htmlentities() function has similar usages.
<?PHP
$str = 'test@gmail.com donated $4 dollars';
echo htmlentities($str); //test@gmail.com &quot;donated $4 dollars
?>

PHP htmlspecialchars_decode() function is the opposite of htmlspecialchars().

<?PHP
$str=htmlspecialchars('<table><tr><td>name<td>address</table>');
echo $str; 
//&lt;table&gt;&lt;tr&gt;&lt;td&gt;name&lt;td&gt;address&lt;/table&gt;
$str2 = htmlspecialchars_decode($str);
echo $str2;
//<table><tr><td>name<td>address</table>
?>