PHP htmlentities() Function

Quick summary: The PHP htmlentities() function converts all applicable characters to HTML entities.

PHP htmlentities() Syntax

htmlentities(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string
PHP

PHP htmlentities() Basic examples

echo htmlentities("© 2024");
PHP
Output:
© 2024

Converts extended characters into HTML entities.

PHP htmlentities() Real-world usage

$text = "München";
echo htmlentities($text, ENT_QUOTES, "UTF-8");
PHP
Output:
München

Encodes non-ASCII characters safely.

PHP htmlentities() Edge cases

echo htmlentities("<b>Hello</b>");
PHP
Output:
&lt;b&gt;Hello&lt;/b&gt;

HTML tags are fully encoded.

PHP htmlentities() Common mistakes

Using htmlentities instead of htmlspecialchars

htmlentities is slower and often unnecessary.

Incorrect
echo htmlentities($input);
Correct
echo htmlspecialchars($input);

Use htmlspecialchars for most HTML escaping needs.

PHP htmlentities() Frequently Asked Questions

What does htmlentities() do in PHP?

htmlentities() converts all applicable characters to HTML entities.

How is htmlentities() different from htmlspecialchars()?

htmlentities() converts more characters, including accented ones, while htmlspecialchars() converts only special HTML characters.

Is htmlentities() safe for user input?

Yes, it helps prevent XSS by encoding characters.

Does htmlentities() affect performance?

It is slightly slower than htmlspecialchars() due to more conversions.

Does htmlentities() modify the original string?

No, it returns a new encoded string.

What encoding should be used with htmlentities()?

UTF-8 is recommended.

Can htmlentities() be reversed?

Yes, using html_entity_decode().

What flags can be used with htmlentities()?

Flags include ENT_QUOTES, ENT_HTML5, and ENT_SUBSTITUTE.

When should you use htmlentities() instead of htmlspecialchars()?

When you need to encode a wider range of characters including non-ASCII.

Does htmlentities() handle Unicode correctly?

Yes, when used with UTF-8 encoding.

What is a real-world use case of htmlentities()?

Encoding full text content for safe HTML display.

Can htmlentities() be used for security?

Yes, but it should be part of a broader security strategy.

PHP htmlentities() Related PHP Functions