简体   繁体   English

如何动态填充 <title>在PHP页面中标记?

[英]How do I dynamically populate the <title> tag in a PHP page?

My code looks like: 我的代码如下:

index.php : index.php

<html>....  
    <title>My page</title>

....

<?php
    switch ($_GET['id']){  
        case "tips":  
            include("tips.php");  
            $title = "Tips";
...

How do I get the title varible to the html title tag? 我如何将标题变为html title标签?

All pages pass through index.php . 所有页面都通过index.php

Do your PHP before your HTML output. 在HTML输出之前进行PHP。

<?php

  switch ($_GET["id"]) {
    case "tips":
      $title = "Tips";
      $page  = "tips.php";
  }

?>
<html>
 <head>
  <title><?php print $title; ?></title>
 </head>
 <body>
  <?php include($page); ?>
 </body>
</html>

You can also do this with output buffering and a little string replacement. 您也可以通过输出缓冲和一些字符串替换来实现。

<?php ob_start('ob_process'); ?>
<html>....  
    <title>{{{TITLE}}}</title>

....

<?php

switch ($_GET['id']){  
  case "tips":  
    include("tips.php");  
    $title = "Tips";
    break;
}

function ob_process($buffer) {
  global $title;
  $buffer = str_replace('{{{TITLE}}}', $title, $buffer);
  return $buffer;
}
< title > <?php echo $title; ?> < /title >

If you cannot use what Ahmet KAKICI suggests, add a script tag which sets document.title 如果您无法使用Ahmet KAKICI的建议,请添加一个脚本标签来设置document.title

<html>....  
    <title>My page</title>

....

<?php
    switch ($_GET['id']){  
        case "tips":  
            include("tips.php");  
            $title = "Tips";
...
?>
<script>top.document.title="<?php=$title?>"</script>

My PHP is rusty, just wanted to suggest document.title 我的PHP生锈了,只想建议document.title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM