PHP-如何在包含header.php之后更改页面标题? [英] PHP - how to change title of the page AFTER including header.php?
问题描述
page.php:
<?php
include("header.php");
$title = "TITLE";
?>
header.php:
header.php:
<title><?php echo $title; ?></title>
我希望在包括头文件之后设置我的标题.是否有可能做到这一点?我在php-fusion电视上看到了一些类似的东西: http://docs.php-fusion.it/temi:output_handling
i want my title to be set AFTER including the header file. Is it possible to do this? I've seen some similiar stuff on php-fusion tvs: http://docs.php-fusion.it/temi:output_handling
推荐答案
扩展Dainis Abols答案以及您对输出处理的问题,
expanding on Dainis Abols answer, and your question on output handling,
请考虑以下内容:
您的header.php的标题标签设置为<title>%TITLE%</title>
;
%"很重要,因为几乎没有人键入%TITLE%,因此您以后可以将其用于str_replace().
your header.php has the title tag set to <title>%TITLE%</title>
;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.
然后,您可以使用输出缓冲区像这样
then, you can use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
那应该做到的.
编辑
我相信盖伊的想法效果更好,因为它会在需要时为您提供默认值,即IE:
I believe Guy's idea works better since it gives you a default if you need it, IE:
- 标题现在为
<title>Backup Title</title>
- 代码现在为:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
这篇关于PHP-如何在包含header.php之后更改页面标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!