logan
logan

Reputation: 8346

Print HTML tags in PHP output

I have HTML tags present inside php variable. I want to print the values as it is. Here is what i tried.

$str = "A 'quote' is <b>bold</b>";

echo htmlentities($str);
// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;

echo $str; //out puts as follows

A 'quote' is bold

But i want to print it as

 A 'quote' is <b>bold</b>

Also, Is there any setting can be done at the TOP of the php page, so that i dont need to use it in every php variables ?

Upvotes: 1

Views: 27720

Answers (5)

Tim
Tim

Reputation: 1

What worked for me was to use the PHP HEREDOC syntax to stuff the html into a PHP string --

<pre>
<?php
$str=<<<HEREDOC
html code including most anything (but not more php)
HEREDOC;
echo htmlentities($str);
?>
</pre>

Upvotes: 0

max-m
max-m

Reputation: 867

If you want to print HTML, don't use htmlentities.

If this is user input, you should still filter it.

Edit:

If you want the browser to show the text as A 'quote' is <b>bold</b>, htmlspecialchars or htmlentities is the correct function to use as they escape the HTML code and the browser will show the tags as you want.

Upvotes: 0

logan
logan

Reputation: 8346

to make it as setting..

<?php

function my_custom_echo($str)
{
echo htmlspecialchars($str);
}

my_custom_echo("<p>what ever I want </P>")


?>

Upvotes: -1

Kamehameha
Kamehameha

Reputation: 5473

This should work -

$str = "A 'quote' is <b>bold</b>";
echo "<xmp>".$str."</xmp>";
//Outputs - A 'quote' is <b>bold</b>

EDIT:

<XMP> is deprecated as was pointed out in the comments, and this seems to be the workaround for it(using the <PRE> tag and htmlentities)-

$str = "A 'quote' is <b>bold</b>";
echo "<pre>".htmlentities($str)."</pre>";
//Outputs - A 'quote' is <b>bold</b>

Upvotes: 3

Shiva
Shiva

Reputation: 6887

Just use

 $str = "A 'quote' is <b>bold</b> ";

echo htmlspecialchars($str);

because htmlentities convert some characters to HTML entities.

You should instead use htmlspecialchars

It replaces characters as below:

'&' (ampersand) becomes &amp;
'"' (double quote) becomes &quot; when ENT_NOQUOTES is not set.
"'" (single quote) becomes &#039; only when ENT_QUOTES is set.
'<' (less than) becomes &lt;
'>' (greater than) becomes &gt;

You can check php fiddle here

Upvotes: 7

Related Questions