[php] How to generate a HTML page dynamically using PHP?

I have a page which displays info about a property, based on the unique ID from the url, searching the mysql database for that ID, getting all the info from that row etc, fairly standard really.

I was wondering if/how I can 'create' a html page for each database row, as I'm assuming this would be better for SEO? Having multiple pages with keywords on rather than one dynamic page?

My properties are added to the database by a form/ upload system on the site, I was thinking creating the page on upload might be easiest, but am open to suggestions!

This question is related to php html mysql dynamic

The answer is


I've been working kind of similar to this and I have some code that might help you. The live example is here and below, is the code I'm using for you to have it as reference.

create-page.php

<?php

// Session is started.
session_start();

// Name of the template file.
$template_file = 'couples-template.php';

// Root folder if working in subdirectory. Name is up to you ut must match with server's folder.
$base_path = '/couple/';

// Path to the directory where you store the "couples-template.php" file.
$template_path = '../template/';

// Path to the directory where php will store the auto-generated couple's pages.
$couples_path = '../couples/';

// Posted data.
$data['groom-name'] = str_replace(' ', '', $_POST['groom-name']);
$data['bride-name'] = str_replace(' ', '', $_POST['bride-name']);
// $data['groom-surname'] = $_POST['groom-surname'];
// $data['bride-surname'] = $_POST['bride-surname'];
$data['wedding-date'] = $_POST['wedding-date'];
$data['email'] = $_POST['email'];
$data['code'] = str_replace(array('/', '-', ' '), '', $_POST['wedding-date']).strtoupper(substr($data['groom-name'], 0, 1)).urlencode('&').strtoupper(substr($data['bride-name'], 0, 1));

// Data array (Should match with data above's order).
$placeholders = array('{groom-name}', '{bride-name}', '{wedding-date}', '{email}', '{code}');

// Get the couples-template.php as a string.
$template = file_get_contents($template_path.$template_file);

// Fills the template.
$new_file = str_replace($placeholders, $data, $template);

// Generates couple's URL and makes it frendly and lowercase.
$couples_url = str_replace(' ', '', strtolower($data['groom-name'].'-'.$data['bride-name'].'.php'));

// Save file into couples directory.
$fp = fopen($couples_path.$couples_url, 'w');
fwrite($fp, $new_file);
fclose($fp);

// Set the variables to pass them to success page.
$_SESSION['couples_url'] = $couples_url;
// If working in root directory.
$_SESSION['couples_path'] = str_replace('.', '', $couples_path);
// If working in a sub directory.
//$_SESSION['couples_path'] = substr_replace($base_path, '', -1).str_replace('.', '',$couples_path);

header('Location: success.php');

?>

Hope this file can help and work as reference to start and boost your project.


Just in case someone wants to generate/create actual HTML file...

$myFile = "filename.html"; // or .php   
$fh = fopen($myFile, 'w'); // or die("error");  
$stringData = "your html code php code goes here";   
fwrite($fh, $stringData);
fclose($fh);

Enjoy!


As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

<?php

 $filename = 'test.html';
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=$filename");
 header("Content-Type: application/octet-stream; ");
 header("Content-Transfer-Encoding: binary");
?>

you can create any .html , .php file just change extention in file name


You dont need to generate any dynamic html page, just use .htaccess file and rewrite the URL.


I suggest you to use URL rewrite mod is enough for your problem,I have the same problem but using URL rewrite mod and getting good SEO response. I can give you a small example. Example is that you consider WordPress , here the data is stored in database but using URL rewrite mod many WordPress websites getting good responses from Google and got rank also.

Example: wordpress url with out url rewrite mod -- domain.com/?p=123 after url rewrite mode -- domain.com/{title of article} like domain.com/seo-url-rewrite-mod

i think you have understood what i want to say you


It looks funny but it works.

<?php 
$file = 'newpage.html';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "<!doctype html><html>
<head><meta charset='utf-8'>
<title>new file</title>
</head><body><h3>New HTML file</h3>
</body></html>
";
// Write the contents back to the file
file_put_contents($file, $current);
?>

I'll just update the code to contain the changes, and comment it to so that you can see what's going on clearly...

<?php   
include("templates/header.htm");   

// Set the default name 
$action = 'index'; 
// Specify some disallowed paths 
$disallowed_paths = array('header', 'footer'); 
if (!empty($_GET['action'])) { 
    $tmp_action = basename($_GET['action']); 
    // If it's not a disallowed path, and if the file exists, update $action 
    if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.htm")) 
        $action = $tmp_action; 
} 
// Include $action 
include("templates/$action.htm"); 

include("templates/footer.htm");

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to dynamic

Please help me convert this script to a simple image slider Declare an empty two-dimensional array in Javascript? Compiling dynamic HTML strings from database Changing datagridview cell color dynamically What is the difference between dynamic programming and greedy approach? Dynamic variable names in Bash Dynamically Add C# Properties at Runtime How to generate a HTML page dynamically using PHP? Change UITableView height dynamically How to create own dynamic type or dynamic object in C#?