PHP htmlspecialchars is not working

Wasim A. picture Wasim A. · Feb 25, 2011 · Viewed 8.4k times · Source
<?php  
    $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);  
    echo $new;  
?>

output should be

& lt;a href=& #039;test& #039;&gt;Test& lt;/a& gt; 

but output is

&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

Answer

Peter Carter picture Peter Carter · Feb 25, 2011

Don't worry. htmlspecialchars() is encoding the < and > characters properly. It is just that when you echo the encoded string to your computer screen, your browser helpfully decodes the characters again. If you view the page source you will see the encoded string.