Display HTML code on web page in PHP

Many of newbies PHP developers find that when they try to show HTML code on the web page using print or echo, the browser will convert the code, run it and output the HTML instead of showing the code.

So the HTML code will not be shown up on the web page. It automatically runs by the browser.

Then how to display HTML code on web page in PHP? How we can figure out the problem? How can we prevent the browser from converting our HTML code?

I am going to tell you how to print or show HTML code on the web page in PHP.

Showing HTML code with its syntax is quite easy. Normally we pass the HTML string directly to a function.

But, if we want to show our code, first of all, we have to convert some predefined characters to HTML entities. This is going to be quite easy.

PHP already has a function which is the htmlspecialchars() function that can convert some predefined characters from a string to HTML entities.

Now see the code below:

   $str = "<h1>Hello World</h1><h2>Hello Friends</h2><strong>Go ahead</strong>";
   $html_code = htmlspecialchars($str);
   echo $html_code;

The above code will print the output on the web page that we can see below:

<h1>Hello World</h1><h2>Hello Friends</h2><strong>Go ahead</strong>

We did it by writing just one line of extra code.

So what the htmlspecialchars() function actually did?

The htmlspecialchars() convert the predefined characters as we can see “<” and “>” to the HTML entities.


Also, read:


Below is the list of predefined characters that will be converted into HTML entities:

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

So I hope, now you can show HTML code on the web page after reading this post. You have seen how easy it is.

Leave a Reply