What are the benefits of using PHP to generate static pages from a database compared to traditional CMS systems?
Generating static pages from a database using PHP can offer faster loading times and reduced server load compared to traditional CMS systems. This approach allows for more control over the content and design of the pages, as well as improved security by reducing the attack surface. Additionally, by pre-generating static pages, it can help with SEO optimization and caching.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Retrieve data from the database
$stmt = $pdo->query('SELECT * FROM pages');
$pages = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through each page and generate a static HTML file
foreach ($pages as $page) {
$filename = 'static/' . $page['slug'] . '.html';
$content = '<html><head><title>' . $page['title'] . '</title></head><body>' . $page['content'] . '</body></html>';
file_put_contents($filename, $content);
}
?>
Related Questions
- How can PHP developers prevent caching issues when using Ajax requests to update content on a webpage?
- What are the advantages of using regular expressions over explode for filtering data from a file name in PHP?
- How can one troubleshoot PHP errors related to missing extensions or exceeded time and memory limits?