动态HTML标题元素

时间:2013-01-03 11:12:10

标签: php html

我正在尝试从PHP动态设置页面的HTML标题。我有一个页面,它根据数据库中的条目设置title元素。我试图根据当前页面的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;

3 个答案:

答案 0 :(得分:2)

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

<?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模式。

答案 1 :(得分:1)

为什么不只是<title><?php echo $jobTitle . '|' . 'Standard Title' ?></title> 其中$jobTitle = $rs2row['fldRoleTitle'];应在上述声明之前的某处声明。

答案 2 :(得分:1)

您可以执行以下操作

添加

<?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
相关问题