What are some best practices for using classes to generate valid HTML code in PHP?

When generating HTML code in PHP, using classes can help organize and streamline the process. To ensure the generated HTML is valid, it's important to properly structure the classes and methods to represent the different HTML elements. By following best practices such as separating content from presentation, using inheritance for common elements, and sanitizing user input, you can create a robust and maintainable system for generating valid HTML code.

class HTMLElement {
    protected $tag;
    protected $attributes = [];

    public function __construct($tag) {
        $this->tag = $tag;
    }

    public function setAttribute($name, $value) {
        $this->attributes[$name] = $value;
        return $this;
    }

    public function render() {
        $html = "<{$this->tag}";
        foreach ($this->attributes as $name => $value) {
            $html .= " {$name}=\"{$value}\"";
        }
        $html .= "></{$this->tag}>";
        return $html;
    }
}

// Example usage
$div = new HTMLElement('div');
$div->setAttribute('class', 'container')->setAttribute('id', 'main-content');
echo $div->render();