抓取header.php的页面名称

时间:2014-05-07 21:09:23

标签: php title

对于我的header.php文件,我想通过php获取<title>并且无法执行此操作。我知道调用常量会起作用,但这意味着我需要多个文件(这是不好的做法)。任何进一步的帮助将不胜感激。

define("HOME", dirname(__DIR__)."index.php"); 
define("ABOUT", dirname(__DIR__)."../about/index.php"); 
define("WORK", dirname(__DIR__)."../work/index.php"); 
define("SERVICES", dirname(__DIR__)."../services/index.php"); 
define("CLIENTS", dirname(__DIR__)."../clients/index.php"); 
define("CONTACT", dirname(__DIR__)."../contact/index.php"); 

$page_titles = array (
    'home_page' => 'Home | Page',
    'about_page' => 'About | Page',
    'work_page' => 'Work | Page',
    'services_page' => 'Services | Page',
    'clients_page' => 'Clients | Page',
    'contact_page' => 'Contact | Page'
);

if (HOME == $page_titles[0]) {
    return $page_titles[0];
}

if (ABOUT == $page_titles[1]) {
    return $page_titles[1];
}

if (WORK == $page_titles[2]) {
    return $page_titles[2];
}

if (SERVICES == $page_titles[3]) {
    return $page_titles[3];
}

if (CLIENTS == $page_titles[4]) {
    return $page_titles[4];
}

if (CONTACT == $page_titles[5]) {
    return $page_titles[5];
}

2 个答案:

答案 0 :(得分:1)

您的页面应该定义自己的标题。但是,如果你真的想这样做,这是一个可能的解决方案:

<强> whatever_page_you_load.php:

define("PAGE", "WHATEVERPAGE");

include("header.php");

<强>的header.php:

$page_names = array(
  "HOME" => "Home Page",
  "WHATEVERPAGE" => "Whatever Page's Name";
);

$title = "Default Title";

if(defined("PAGE") && !empty($page_names[PAGE])) {
  $title = $page_names[PAGE];
}

echo "<title>" . htmlentities($title) . "</title>";

答案 1 :(得分:0)

在我用其值切换变量名称后,您的代码如下所示:

if (dirname(__DIR__)."index.php" == 'Home | Page'){
    return 'Home | Page';
}

声明dirname(__DIR__)."index.php" == 'Home | Page'中的条件永远不会评估为true

为特定页面设置特定标题的一个示例是在URL中传递页面名称,然后相应地显示页面名称:

$titles = [
    'home' => 'Home title',
    'contact' => 'Contact title',
    // Other titles omitted    
];

$page = 'home';
if (array_key_exists('page', $_GET) && array_key_exists($_GET['page'], $titles)){
    $page = $_GET['page'];
}

echo '<title>' . $titles[$page] . '</title>';