What are the differences between using htmlentities and htmlspecialchars for escaping characters in PHP?

When escaping characters in PHP, both htmlentities and htmlspecialchars can be used to prevent XSS attacks by converting special characters to their HTML entities. The main difference between the two functions is that htmlentities converts all applicable characters to HTML entities, while htmlspecialchars only converts a select few characters (such as <, >, ", ', &) to their HTML entity equivalents.

// Using htmlentities to escape characters
$unsafe_string = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_string = htmlentities($unsafe_string);
echo $safe_string;
```

```php
// Using htmlspecialchars to escape characters
$unsafe_string = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_string = htmlspecialchars($unsafe_string);
echo $safe_string;