What role does a template system play in simplifying the output of query results in PHP, and how can it be effectively integrated into the code?
Using a template system in PHP can simplify the output of query results by separating the presentation logic from the business logic. This allows for easier maintenance and updates to the UI without affecting the underlying code. To integrate a template system effectively, you can create a separate template file with placeholders for dynamic data and use a templating engine like Twig to render the final output.
```php
// Example code using Twig template engine
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);
$queryResults = [
['name' => 'John Doe', 'age' => 30],
['name' => 'Jane Smith', 'age' => 25],
['name' => 'Alice Johnson', 'age' => 35]
];
echo $twig->render('results.html', ['results' => $queryResults]);
```
In this code snippet, we are using the Twig template engine to render the query results stored in the `$queryResults` array. The `results.html` template file contains placeholders for the name and age fields, which are replaced with the actual data when rendered using Twig. This separation of concerns makes it easier to manage and update the UI without modifying the PHP code.