The PHP htmlentities is an inbuilt function in PHP. It transforms all existing characters to their corresponding HTML Entities where applicable. In this article, we will discuss the PHP htmlentities Function. Also, we will discuss a few examples of using it.
Note: To convert HTML entities back to characters, use the PHP html_entity_decode Function.
Syntax
string htmlentities( $string, $flags, $encoding, $double_encode )
Parameters
The PHP htmlentities Function expects four parameters. However, only one parameter is mandatory and rest three are optional. The description of the parameters is as follows:
- $string: The first parameter specifies the input string to convert.
- $flags: The second parameter specifies how to handle quotes. It is a combination of two or more flags. You can refer to the list of all the available flags on PHP.net.
- $encoding: The third parameter specifies the encoding to use while converting. By default, the function uses the default PHP encoding. You can refer to the supported encoding parameters on PHP.net.
- $double_encode: The fourth parameter specifies whether to encode already existing HTML entities. By default, the function encodes everything. However, on turning off, the function will not encode existing HTML entities.
Return Value
The PHP htmlentities Function returns the string after encoding and transforming characters into HTML entities. However, it returns an empty string if there is an error if the string contains an invalid code sequence.

Examples
Let’s consider a few examples of using the function.
Example 1: Simple Encoding
For instance, consider an example of encoding a simple html string.
<?php $htmlString = '<a href="concatly.com">Concatly\'s Blog</a>'; echo htmlentities($htmlString); ?>
The above script prints the following. Also, notice the single quote is present as it is.

Example 2: Converting Quotes
Also, you can convert single quotes by passing the second parameter as ENT_QUOTES.
<?php $htmlString = "This is a 'quote'"; echo htmlentities($htmlString); echo htmlentities($htmlString, ENT_QUOTES); ?>
In the above example, notice the difference on the single quote on passing ENT_QUOTES flag.

Conclusion
In conclusion, we discussed the PHP htmlentities Function in this article. You can read more about it on the Official PHP Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.