How can PHP developers ensure that URLs are both URL-conform and HTML-safe when used in HTML attributes?

To ensure that URLs are both URL-conform and HTML-safe when used in HTML attributes, PHP developers can use the htmlspecialchars() function to encode the URL before outputting it in the HTML. This function will convert special characters in the URL to their corresponding HTML entities, preventing any potential XSS attacks or rendering issues.

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