What are the best practices for organizing and structuring PHP code that generates HTML elements dynamically?

When generating HTML elements dynamically in PHP, it is important to follow best practices for organizing and structuring the code to ensure readability, maintainability, and scalability. One common approach is to separate the PHP logic from the HTML markup by using a template engine like Twig or Blade. This allows for cleaner code, easier debugging, and better separation of concerns.

```php
<?php
// Example using Twig template engine
require_once 'vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);

$data = [
    'title' => 'Dynamic HTML Example',
    'items' => ['Item 1', 'Item 2', 'Item 3']
];

$template = $twig->load('dynamic_html.twig');
echo $template->render($data);
```

In this code snippet, we are using the Twig template engine to separate the PHP logic from the HTML markup. The template file "dynamic_html.twig" contains the HTML structure with placeholders for dynamic data. We pass the data array to the template, and Twig handles rendering the HTML with the dynamic content. This approach makes the code more organized and easier to maintain.