DevToolsForYou

HTML Escape Tool in PHP — Code Examples

HTML Escape Tool in PHPUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) 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
<?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";
// &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

// 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&eacute; &amp; r&eacute;sum&eacute;

// Decode all entities back
$decoded = html_entity_decode($all, ENT_QUOTES | ENT_HTML5, "UTF-8");
echo $decoded . "\n"; // café & résumé
Notes & gotchas
  • 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.
Try it in your browser

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 other languages