Codectionary / Developer documentation / PHP

PHP HTML output escaping

htmlspecialchars converts HTML-significant characters when inserting text into HTML. Escaping belongs at the output boundary and must match the output context.

Syntax

htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8")

Examples

PHP HTML output escaping

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$label = 'Ada & <Lin>';
$safe = htmlspecialchars($label, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo '<p>', $safe, '</p>', PHP_EOL;
  1. CLI output: <p>Ada &amp; &lt;Lin&gt;</p>. An HTML renderer displays the original text without interpreting <Lin> as markup.

Best practices

  • Use this for HTML text and properly quoted ordinary attributes. JavaScript, CSS and URLs need their own context-specific handling.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading