如何在包含标头后动态更改TITLE

时间:2014-07-16 21:42:43

标签: php html

我想根据内容更改HTML页面的标题,但是我只包括标题部分下面的内容,所以我必须更改包含php的标题。解释:

<html>

<header><title>I would like to change</title></header>
<!--CONTENT-->
        <?
        include "pages/some_page.php";
        ?>
</html>

我怎么能这样做?任何人都可以帮忙吗?

4 个答案:

答案 0 :(得分:2)

如果没有讨厌的黑客行为,你就无法做到这一点。

你应该做的是在输出html之前执行所有逻辑。一个简单的例子如下:

<?php
//index.php
//perform logic and set variables before any html

$page = isset($_GET['menu'])?$_GET['menu']:'home';

switch($page){
    case 'home':
        $title = ' welcome to myco.ltd';
        $content = 'pages/home.php';
        break;
    case 'about':
        $title = 'about us';
        $content = 'pages/about.php';
        break;
    case 'contact':
        $title = 'get in touch';
        $content = 'pages/contact.php';
        break;
}
//the following html could be in a separate file and included, eg layout.php
?>
<html>
<head>
    <title><?php echo $title;?></title>
</head>
<body>
<!--menu and other shared html here-->
<?php include $content;?>
<!-- shared footer stuff here-->
</body>
</html>

这本质上是一个非常简单的路由器脚本,是任何框架的重要组成部分。我强烈建议你考虑一个轻量级的框架,而不是从头开始编写所有内容。 http://fatfreeframework.com/home将是一个很好的开始

答案 1 :(得分:1)

以下功能可让您更改文档标题,元关键字和元描述。您可以在应用程序的任何位置使用它。

在调用函数之前,务必使用ob_start()打开输出缓冲。在加载所有全局设置之后,我更喜欢将它包含在应用程序的顶部。

function change_meta_tags($title, $keywords, $description){

    $output = ob_get_contents();
    if (ob_get_length() > 0) { ob_end_clean(); }

    $patterns = array("/<title>(.*?)<\/title>/", "/<meta name=\"keywords\" content=\"(.*?)\" \/>/", "/<meta name=\"description\" content=\"(.*?)\" \/>/");
    $replacements = array("<title>$title</title>", "<meta name=\"keywords\" content=\"$keywords\" />", "<meta name=\"description\" content=\"$description\" />");

    $output = preg_replace($patterns, $replacements, $output);  
    echo $output;
}

答案 2 :(得分:0)

在some_page.php中使用javascript。

<?php echo "<script>document.title = '".$dynamicTitleVariable."';</script>"; ?>

答案 3 :(得分:0)

在您尝试将内容作为基础之前,可以通过MVC风格的设置轻松完成。在您的控制器中,您将根据可以抓取的内容生成标题,并将其作为变量传递给视图。然后,在您的视图中,动态设置标题:

<html>
    <head>
        <title>
            <?php echo $title; ?>
        </title>
    </head>
</html>

这也适用于SEO功能,因为抓取工具能够比JavaScript更好地解释这一点。