What best practices should be followed when dynamically changing titles and meta tags for different subpages in PHP?

When dynamically changing titles and meta tags for different subpages in PHP, it is best practice to use a function that generates these tags based on the specific content of each subpage. This ensures that search engines can properly index and display the correct information for each page. Additionally, it is important to sanitize any user input to prevent XSS attacks and ensure the security of the website.

<?php
function generateMetaTags($pageTitle, $description, $keywords) {
    $output = "<title>{$pageTitle}</title>";
    $output .= "<meta name='description' content='{$description}'>";
    $output .= "<meta name='keywords' content='{$keywords}'>";
    
    return $output;
}

// Example usage
$pageTitle = "Home Page";
$description = "Welcome to our website!";
$keywords = "PHP, web development, best practices";

echo generateMetaTags($pageTitle, $description, $keywords);
?>