HTML Escape Tool in PHP — Code Examples
HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (<, >, &, ") to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.
PHP provides htmlspecialchars for escaping the five critical characters and htmlentities for full entity encoding. Always pass ENT_QUOTES.
<?php
$raw = '<script>alert("xss")</script> & "quotes"';
// Escape (ENT_QUOTES escapes both " and ')
$escaped = htmlspecialchars($raw, ENT_QUOTES | ENT_HTML5, "UTF-8");
echo $escaped . "\n";
// <script>alert("xss")</script> & "quotes"
// Unescape
$unescaped = htmlspecialchars_decode($escaped, ENT_QUOTES | ENT_HTML5);
echo $unescaped . "\n";
// htmlentities() encodes ALL HTML entities (including accented characters)
$all = htmlentities("café & résumé", ENT_QUOTES | ENT_HTML5, "UTF-8");
echo $all . "\n"; // café & résumé
// Decode all entities back
$decoded = html_entity_decode($all, ENT_QUOTES | ENT_HTML5, "UTF-8");
echo $decoded . "\n"; // café & résumé- Always pass ENT_QUOTES to escape both single and double quotes, preventing attribute injection attacks.
- Always specify the charset (UTF-8) explicitly to avoid encoding-based bypass attacks.
- htmlspecialchars escapes only the five critical characters; use htmlentities if you need full entity encoding for non-ASCII content.
Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.
Open HTML Escape/Unescape →HTML Escape Tool in JavaScript / Node.js
In browsers, create a temporary DOM element to escape HTML reliably. In Node.js, use a library like he or escape manually.
HTML Escape Tool in Python
Python's standard library includes the html module with html.escape and html.unescape. No third-party packages needed.
HTML Escape Tool in Go
Go's html package provides EscapeString and UnescapeString. Both handle the five critical HTML characters.
HTML Escape Tool in Java
Java's standard library lacks an HTML escaping utility. Use Apache Commons Text (StringEscapeUtils) or Spring's HtmlUtils.
HTML Escape Tool in Ruby
Ruby's CGI module provides CGI.escapeHTML and CGI.unescapeHTML. Rails adds the h helper and auto-escapes ERB output by default.
HTML Escape Tool in Rust
The html-escape crate provides encode_text and decode_html_entities. For template rendering, askama and minijinja auto-escape by default.
HTML Escape Tool in C# / .NET
C# provides WebUtility.HtmlEncode in System.Net (all .NET targets) and HttpUtility.HtmlEncode in System.Web (ASP.NET only).