I am trying to set the HTML title of a page dynamically from PHP. I have a page which sets the title element based upon an entry in a database. I am trying to make the title change dynamically based on the current page’s H2 content. This content is, once again, retrieved from the database.
I have tried to do this using session variables, but obviously due to the load order this doesn’t work as the header is loaded, and then the content. On page refresh the title is then set correctly, but this is not good.
I currently am using JavaScript to update the title but again this is no good for search engine bot that don’t have JS enabled.
PHP
session_start(); <--both header and dynamic page -->
<title><?php echo $_SESSION['dynamictitle'];?></title> <-- Header -->
$jobTitle = $rs2row['fldRoleTitle']; <-- dynamic page -->
$_SESSION['dynamictitle'] = $jobTitle;
JavaScript
var currentTitle = "<?php Print($jobTitle) ?>" + " | " + document.title;
document.title = currentTitle;
Separate the loading and processing of the data for the template from the actual output/rendering of the template, e.g. determine the variables before putting them in the template, e.g.
And then just echo the variables in the respective templates, e.g.
and whatever should go into templateForThisPage.html then. This is much more convenient and sane to maintain than having a linear script mixing data fetching, processing and output in one big messy file. If you want to extend on this approach, consider reading about the MVC pattern.