问题原文
原帖链接 · OverLordGoldDragon · CC BY-SA 4.0
My PHP-based site files start off with
<?php include("PHP/header.php"); ?>
which includes all the HTML (metadata, scripts, etc.) shared by every page - along <head> and <title>. The options I've considered for dynamic page titles are:
<title id="title">...</title>
...
<script>window.onload=function(){document.getElementById('title').innerHTML="New title"}
</script>
and
<?php include("PHP/header1.php"); ?> <!-- code in header.php before <title> -->
<title>New title</title>
<?php include("PHP/header2.php"); ?> <!-- code after </title> -->
(I intend the same for page descriptions - omitted for brevity.)
Which of these is preferable for search engine optimization - do better approaches exist? Lastly, any performance differences to note (scripts vs. php, etc)?
已采纳解答
原帖链接 · Stephen Ostermiller · CC BY-SA 4.0
Set the title as a variable and pass it to your include:
<?php
$page_title = 'Welcome to my site';
include("PHP/header.php");
?>
Then inside your header PHP you can use that variable. Here I'm using htmlspecialchars to ensure that <>& are properly escaped if they are used in the title.
<title><?php echo htmlspecialchars($page_title); ?></title>
You could even put code in your header PHP to check that the title has been set and to use a default title if it hasn't been:
if (empty($page_title)) {
$page_title = 'This page gets this default title';
}
You could use the same technique for other items that you might want to customize in the header such as the meta description.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
