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;- CLI output: <p>Ada & <Lin></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