What are the best practices for encoding URLs in PHP to prevent invalid HTML output?

When encoding URLs in PHP to prevent invalid HTML output, it is important to use the `htmlspecialchars()` function to escape special characters in the URL. This helps prevent cross-site scripting (XSS) attacks and ensures that the URL is properly displayed in HTML without causing any parsing errors.

$url = 'https://www.example.com/page?param1=value1&param2=value2';
$encoded_url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
echo '<a href="' . $encoded_url . '">Link</a>';