SHARE

How to add HTML tag as string in php

Generally when you try to add html tag as sting in php and run php code , the php rendered this tag as html tag but not as string .

Example:

<html>
<head>
</head>
<body>
<?php
$a = "<h1> This is heading </h1>";
echo $a;
?>
</body>
</html>

In the above code variable $a value is a string . But in this string <h1>and</h1> tags are the html tags . When you run this code .

Result of the code is as following image . <h1> </h1> tags are rendered as html tags and display text as heading “This is heading“and no <h1></h1> tags are displayed .

PHP html tags
PHP html tags

To prevent these html tags from rendering and display them as string htmlentities() is required .

htmlentities()

htmlentities() is a built in function in PHP . To use this function you have no need to define or create this function .

Example

<html>
<head>
</head>
<body>
<?php
$a = "<h1> This is heading </h1>";
echo htmlentities($a);
?>
</body>
</html>
htmlentities()
htmlentities() function in php

In this php code string is stored in variable and variable is used as argument of function htmlentities($a) . It prevent html tags to rendered as html tags .And tags are displayed as string as shown in upper image .