What are the potential pitfalls of using htmlentities() for protection against XSS in PHP?

Using htmlentities() alone may not provide complete protection against XSS attacks as it only converts certain characters to HTML entities. To ensure better protection, it is recommended to use htmlspecialchars() instead, which converts special characters to their HTML entity equivalents and also considers the context in which the data is being used.

// Using htmlspecialchars() for better protection against XSS attacks
$unsafe_data = $_POST['input_data'];
$safe_data = htmlspecialchars($unsafe_data, ENT_QUOTES, 'UTF-8');