Open In App

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

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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 GeeksforGeeks&lt;/h1&gt;";

$decodedStr = html_entity_decode($htmlEntities);

echo $decodedStr;

?>

Output
<h1>Welcome to GeeksforGeeks</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 GeeksforGeeks&lt;/h1&gt;";

$decodedStr = htmlspecialchars_decode($htmlEntities);

echo $decodedStr;

?>

Output
<h1>Welcome to GeeksforGeeks</h1>

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads