What best practices should be followed when creating a function to generate dynamic HTML elements in PHP?

When creating a function to generate dynamic HTML elements in PHP, it is important to follow best practices to ensure clean and maintainable code. One key practice is to separate the HTML structure from the PHP logic by using concatenation or heredoc syntax. Additionally, consider using parameters to customize the generated elements and make the function reusable. Lastly, sanitize any user input to prevent security vulnerabilities such as cross-site scripting (XSS) attacks.

<?php
function generateDynamicElement($element, $content, $attributes = array()) {
    $html = "<$element";
    
    foreach ($attributes as $key => $value) {
        $html .= " $key=\"$value\"";
    }
    
    $html .= ">$content</$element>";
    
    return $html;
}

// Example usage
echo generateDynamicElement('div', 'Hello World', array('class' => 'container', 'id' => 'hello'));
?>