Is using htmlentities to sanitize input fields in PHP the most effective approach, or are there more elegant solutions available?

Using htmlentities to sanitize input fields in PHP is a good approach to prevent XSS attacks by converting special characters to HTML entities. However, it may not be the most elegant solution as it can sometimes be overly aggressive in its encoding. Another approach is to use functions like filter_input or filter_var with specific filters to sanitize input fields more selectively and effectively.

// Example using filter_input to sanitize input fields
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

// Example using filter_var to sanitize input fields
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);