What are some best practices for generating HTML links dynamically in PHP?

When generating HTML links dynamically in PHP, it is important to properly escape any user input to prevent XSS attacks and ensure the links are valid. One best practice is to use the htmlspecialchars() function to escape the URL parameters before outputting them in the link.

$url = "https://www.example.com";
$text = "Click Here";

echo '<a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($text) . '</a>';