How can PHP functions be structured to efficiently replace placeholders in HTML templates with dynamic content retrieved from a database?
To efficiently replace placeholders in HTML templates with dynamic content retrieved from a database, you can create a PHP function that fetches the dynamic content from the database and replaces the placeholders in the HTML template. This function should accept the template file path, placeholders array, and database connection as parameters. It should read the template file, replace the placeholders with the dynamic content, and then output the modified HTML.
function replacePlaceholders($templatePath, $placeholders, $dbConnection) {
$html = file_get_contents($templatePath);
foreach($placeholders as $placeholder => $value) {
$html = str_replace("{{" . $placeholder . "}}", $value, $html);
}
// Fetch dynamic content from database here using $dbConnection
echo $html;
}
// Example usage
$templatePath = "template.html";
$placeholders = array(
"title" => "Dynamic Title",
"content" => "Dynamic Content"
);
$dbConnection = mysqli_connect("localhost", "username", "password", "database");
replacePlaceholders($templatePath, $placeholders, $dbConnection);