tags:

views:

58

answers:

2

I want to display the output of PHP echo statement on the browser. The result is output of htmlentities() function of PHP.

$str = "A 'quote' is <b>bold</b>";
// Expected Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo "<textarea>".htmlentities($str)."</textarea>";
// Expected Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo "<textarea>".htmlentities($str, ENT_QUOTES)."</textarea>";

Apparently, it is giving me

A 'quote' is <b>bold</b> inside my <textarea>

Please advise.

+2  A: 

Double-escape it.

echo "<textarea>".htmlentities(htmlentities($str))."</textarea>";

The purpose of htmlentities() is to prevent HTML being parsed as-is. But you actually want to display the HTML entities as-is, so you need to re-escape them in turn.

BalusC
+1  A: 

BalusC's solution will work, or you could just write your string as you want it to appear and continue to use htmlentities only once:

    $str = "A 'quote' is &lt;b&gt;bold&lt;/b&gt;";

    echo "<textarea>".htmlentities($str)."</textarea>";

    // Expected Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
    // Actual Output   : A 'quote' is &lt;b&gt;bold&lt;/b&gt;
typoknig