动态HTML标题元素

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.

<?php // handlerForThisPage.php

    session_start();
    $dynamicTitle = $_SESSION['dynamictitle'];
    …
    $jobTitle = $rs2row['fldRoleTitle'];
    …

    include '/path/to/header.html';
    include '/path/to/templateForThisPage.html';

And then just echo the variables in the respective templates, e.g.

// header.html
<html>
    <head>
        <title><?php echo $dynamicTitle ?></title>
         …

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.

Why dont you just <title><?php echo $jobTitle . '|' . 'Standard Title' ?></title> where $jobTitle = $rs2row['fldRoleTitle']; should be declared somewhere before above statement.

You can do the following

add

<?php 
ob_start();  
?>

at the first line of the document before your header;

then put title as follows: {title_holder}

then after your title is ready in your code do the following:

<?php
// Catch all the output that has been buffered 
$output = ob_get_contents();
// clean the buffer to avoid duplicates
ob_clean();
// replace the title with the generated title
$output = str_replace('{title_holder}', 'Your title here',$output);
// put the html back in buffer
echo $output

?>
// Then continue your code