动态HTML标题元素


Dynamic HTML title element

我试图从PHP动态设置页面的HTML标题。我有一个页面,其中设置基于数据库中的条目标题元素。我试图使标题根据当前页面的H2内容动态变化。该内容同样是从数据库中检索的。

我试过使用会话变量来做到这一点,但显然由于加载顺序,这不起作用,因为头被加载,然后是内容。在页面刷新时,标题设置正确,但这并不好。

我目前正在使用JavaScript来更新标题,但这对于没有启用JS的搜索引擎机器人来说没有好处。

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;

将模板的数据加载和处理与模板的实际输出/呈现分开,例如,在将变量放入模板之前确定变量,例如

<?php // handlerForThisPage.php
    session_start();
    $dynamicTitle = $_SESSION['dynamictitle'];
    …
    $jobTitle = $rs2row['fldRoleTitle'];
    …
    include '/path/to/header.html';
    include '/path/to/templateForThisPage.html';

然后回显相应模板中的变量,例如

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

和任何应该放在templateForThisPage.html中的内容。这比在一个大而混乱的文件中混合数据获取、处理和输出的线性脚本要方便和合理得多。如果您想扩展这种方法,请考虑阅读MVC模式。

为什么不直接使用<title><?php echo $jobTitle . '|' . 'Standard Title' ?></title>呢其中$jobTitle = $rs2row['fldRoleTitle'];应在上述语句之前的某处声明

您可以执行以下操作

添加
<?php 
ob_start();  
?>

在文档头前的第一行;

{title_holder}

然后在代码中准备好标题后执行以下操作:

<?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