How to Convert Special HTML Entities Back to Characters in PHP?

Sometimes, when we work with HTML in PHP, you may encounter special characters that are represented using HTML entities. These entities start with an ampersand (&) and end with a semicolon (;). For example, &lt; represents <, &gt; represents >, and &amp; represents &. To convert these HTML entities back to their original characters, you can use PHP’s built-in functions such as html_entity_decode() and htmlspecialchars_decode(). In this article, we will explore both approaches with explanations and code examples.

Table of Content

  • Using html_entity_decode() Function
  • Using htmlspecialchars_decode() Function

Approach 1: Convert HTML Entities to Characters using html_entity_decode() Function

The html_entity_decode() function converts HTML entities to their corresponding characters. It takes an optional second parameter $flags to specify how to handle quotes and which character set to use.

PHP
<?php

$htmlEntities = "&lt;h1&gt;Welcome to w3wiki&lt;/h1&gt;";

$decodedStr = html_entity_decode($htmlEntities);

echo $decodedStr;

?>

Output
<h1>Welcome to w3wiki</h1>

Approach 2: Convert HTML Entities to Characters using htmlspecialchars_decode() Function

The htmlspecialchars_decode() function converts special HTML entities back to characters. It is useful when dealing with encoded strings that were created using htmlspecialchars().

PHP
<?php

$htmlEntities = "&lt;h1&gt;Welcome to w3wiki&lt;/h1&gt;";

$decodedStr = htmlspecialchars_decode($htmlEntities);

echo $decodedStr;

?>

Output
<h1>Welcome to w3wiki</h1>

Contact Us