How to display HTML code on a web page?

by Yang Yang on August 4, 2009

Web pages are made up of HTML code, so if you post or write some HTML code in a web pages, a browser would generally consider them normal code. Instead of showing them as they are literally, they have become part of the underlying HTML structure of that page.

Now how to address this problem and display HTML code and HTML tags correctly in a web page as the page content?

The answer is, use HTML entities.

HTML entities are a way to encode special HTML characters such as < and > into literal characters that cannot be interpreted by browsers as HTML code. Refer to the most common HTML entities conversion table below:

  • ‘&’ (ampersand) becomes ‘&amp;
  • ‘"’ (double quote) becomes ‘&quot;
  • ”’ (single quote) becomes ‘&#039;
  • ‘<’ (less than) becomes ‘&lt;
  • ‘>’ (greater than) becomes ‘&gt;

Therefore, to display HTML code as they are and show them to your web site visitors, write the special characters such as < and > in HTML entities. For example,

<h2>Beautiful town</h2>

Has to be written:

&lt;h2&gt;Beautiful town&lt;/h2&gt;

There are of course handy tools you can use to make these conversions much easier. PHP has a function, htmlentities() that accepts normal HTML code and converts them into HTML entities. You can also rely on online tools to make that happen.

Subscribe to Kavoir: blog feed

You should also read:

sanjay October 22, 2009 at 12:42 pm

<h1>

The time is:

</h1>

<br>

<table bordercolor="#FFCC00" border="1">

<tr>

<td>

<div id="clock" class="clock">

Yang Yang January 26, 2010 at 1:36 pm

What are you doing?

bruce lim February 13, 2010 at 8:24 am

you can put whatever code in here you want.
or xml code, i guess whatever that has to get escaped with htmlentities will work.
can’t ask my why tho, cause i don’t know. it just works. its voodoo.

bruce lim February 13, 2010 at 8:24 am

damn it knew it i cant put html in there any ways.

bruce lim February 13, 2010 at 8:26 am

try <pre><xmp> with html code here </xmp></pre>

Yang Yang February 26, 2010 at 6:12 pm

As far as I know, <xmp> has been deprecated.

Ram November 10, 2012 at 4:01 pm

Thanx its working fine …

Vinkesh Tilokani January 27, 2011 at 11:15 am

@bruce lim –
Thank You !!
You almost solved my headache. Nice work. . . :) :)

deb and suks January 31, 2011 at 3:20 pm

this is of no use Damn it

Gordon May 30, 2011 at 6:49 am

That’s great bruce worked a treat for me.
Nice one. Thanks.

Akhil July 19, 2011 at 8:25 pm

Great. Thanks.

Rahoof PM April 17, 2012 at 5:05 pm

very nice post. thanks for your valuable information.

poulson September 2, 2012 at 11:43 pm

Good, Thanks

Comments on this entry are closed.

{ 2 trackbacks }

Previous post:

Next post: