What are the best practices for securing HTML attributes when generating dynamic URLs in PHP?

When generating dynamic URLs in PHP, it's important to properly secure HTML attributes to prevent cross-site scripting (XSS) attacks. One way to do this is by using the htmlspecialchars() function to encode special characters in the attribute values.

$dynamicUrl = "https://example.com/page?param=" . htmlspecialchars($paramValue, ENT_QUOTES, 'UTF-8');
echo '<a href="' . $dynamicUrl . '">Link</a>';