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:
<?php $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.
- How To Rename A File in PHP
- Dark Sky Weather Forecast PHP Script by CodeSpeedy
- How to get last modification time of a file in PHP
Below is the list of predefined characters that will be converted into HTML entities:
- & (ampersand) converts to &
- ” (double quote) converts to "
- ‘ (single quote) converts to '
- < (less than) converts to <
- > (greater than) converts to >
So I hope, now you can show HTML code on the web page after reading this post. You have seen how easy it is.