How to generate a HTML page dynamically using PHP?

How to generate a HTML page dynamically using PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Static HTML Pages for Dynamic Data

You are currently fetching property data from a MySQL database based on an ID in the URL, then rendering that information into an HTML response stream directly from PHP. This is a functional approach, but it introduces significant performance bottlenecks as traffic scales. Every request requires a database query, active PHP execution time, and server-side template rendering before sending bytes to the client. If you want to improve SEO by ensuring every property has its own canonical URL indexed independently, static generation becomes a compelling architectural shift.

The core question is whether to generate these files during the initial data upload or on-demand via a CLI tool. Creating pages immediately upon form submission is technically simpler and ensures content exists instantly. However, it tightly couples your write path with your deployment strategy. If you rely solely on this method, you must ensure your web server handles file permissions correctly for the storage or public directory where these HTML files will reside. More critically, if a property is edited later in the database, the static file becomes stale until another upload occurs or you implement a background job to re-render it.

A more robust pattern involves separating concerns: keep your application logic focused on data manipulation and let a dedicated process handle static generation. You can build a simple CLI command that queries all properties, iterates through them, and writes an HTML file to disk for each one. This decouples the rendering process from user traffic. You might schedule this via Cron to run after every upload or batch update, ensuring your static site is always up to date without impacting response times during peak hours.

Here is a practical implementation pattern using PHP's fopen and fwrite functions to write files directly:

#!/usr/bin/env php
<?php

// Ensure the script can only be run from CLI for safety
if (php_sapi_name() !== 'cli') {
    exit('This script must be run from the command line.');
}

try {
    // Connect to your database
    $pdo = new PDO('mysql:host=localhost;dbname=properties', 'user', 'pass');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch all properties or a specific batch
    $stmt = $pdo->query("SELECT id, title, description, price, image_url FROM properties ORDER BY created_at DESC");
    $properties = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($properties as $prop) {
        $filePath = "public/property_" . $prop['id'] . ".html";
        
        // Start writing the file
        $fileHandle = fopen($filePath, 'w') or die("Unable to write to $filePath");

        // Generate the HTML content using a template string or include
        $template = <<<'HTML'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{$prop['title']}</title>
</head>
<body>
    <h1>{$prop['title']}</h1>
    <p>{$prop['description']}</p>
    <span class="price">${$prop['price']}</span>
    <img src="$prop['image_url']" alt="Property Image">
</body>
</html>
HTML;

        // Replace placeholders with actual data
        $content = str_replace(
            ['{title}', '{description}', '{price}', '{image_url}'],
            [$prop['title'], $prop['description'], $prop['price'], $prop['image_url']],
            $template
        );

        fwrite($fileHandle, $content);
        fclose($fileHandle);
        
        echo "Generated: $filePath\n";
    }

} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}

This script demonstrates the mechanical process of iterating through a dataset and persisting it to disk. However, you must consider the trade-offs regarding URL structure. If your database ID is 12345, generating a file named property_12345.html works, but search engines often prefer human-readable slugs like property-12345-london-flat.html. Your generation logic needs to include a mapping step where you query the database for existing slug values or generate unique ones on the fly.

Another critical consideration is caching. If your site serves these static files directly via Apache or Nginx, you will see a massive reduction in server load and latency. The only time PHP executes is when the database changes and you trigger a regeneration. For high-traffic sites, implementing versioning (e.g., property_12345_v1.html) can prevent issues where content updates haven't propagated to the static layer yet.

If you are already using the Laravel framework, this pattern aligns well with Blade templates and Artisan commands. You could create a custom Artisan command that accepts an optional ID argument. If no ID is provided, it regenerates all pages. This keeps your logic within the framework's ecosystem while still offloading heavy I/O tasks to the CLI environment.

Ultimately, the decision between on-upload generation and scheduled batch processing depends on your site's volatility. Real estate listings rarely change mid-day, making a post-upload trigger efficient. However, if you manage inventory that updates frequently via API or bulk imports, a nightly cron job ensures consistency without relying on user actions.

Our network