【问题标题】:Set Page Title using PHP使用 PHP 设置页面标题
【发布时间】:2011-03-28 16:22:39
【问题描述】:

我希望将我的网页标题设置为 Ultan.me - 无论帖子标题如何。我希望它显示帖子标题。帖子被提交到 MySQL 数据库,标题行称为“标题”。对这个小问题的任何帮助表示赞赏。

更新:

这是页面本身,但它不显示标题。我应该打开 php 文档并连接到与当前位置不同的数据库吗?

代码(唯一必要的部分是开头):

<html>
<head>

<meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
<title>Ultan.me - <?echo $title;?></title>

<link rel="stylesheet" href="css/styles.css" type="text/css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" 
src="js/jquery.labelify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(":text").labelify();
});
</script>
<style>
a {text-decoration:none}

</style>
</head>
<body>
<div id="main">

<!-- Menu Start -->
<div id="menu">
<ul>
<li><a href="index.php">home</a></li>
<li><a href="index.php">about me</a></li>
<li><a href="index.php">archives</a></li>
<li><a href="index.php">contact</a></li>
<li><a href="index.php">gallery</a></li>

</ul>
</div>
<!-- Menu End --> 

<img src="images/banner.png" />
<div id="content">
<div id="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid ID specified.");
}

$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";

$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $row[category]");
    $category = mysql_fetch_array($get_categories);


    ?>
<p><?php echo "<p id='post-title'><strong><a href=\"post.php?id=". $id . "\">" . $title . "</a></strong></p>"; ?><br /><br />
<div id="entry"><?php echo $entry; ?>
</div><br /><br />
<p id="date">Posted in <a href="category.php?category=<?php echo $row['category']; ?>"><?php echo $category['category_name']; ?></a> on <?php echo $date; ?></p>
</p>
<h2 id="share-title">Share This Post</h2>
<div id="social-share">
<li id="link-right"><a href="http://twitter.com/home?status=
I just read <?php echo $title; ?> at http://ultan.me/post.php?id=<?php echo $id; ?>"><center>Twitter</center></a></li>
<li id="link-left"><a href="http://digg.com/submit?url=http://ultan.me/post.php?id=<?php echo $id; ?>"><center>Digg</center></a></li>
<br>
<li id="link-right"><a href="http://www.facebook.com/sharer.php?u=http://ultan.me/post.php?id=<?php echo $id; ?>&t=<?php echo $title; ?>"><center>Facebook</center></a></li>
<li id="link-left"><a href="http://www.google.com/buzz/post?url=http://ultan.me/post.php?id=<?php echo $id; ?>
"><center>Google Buzz</center></a></li>
<div class="clr"></div>
</div>
<h2 id="comments-title">Comments</h2>
 <div id="comment-list">
    <?php

}
$commenttimestamp = strtotime("now");

$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
    $timestamp = date("l F d Y", $row['timestamp']);
      printf("<div class='comment-ind'><p id='comments'><a id='username' href=\"%s\">%s</a> %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
    print("<p class='comments'>" . stripslashes($row['comment']) . "</p><div class='clr'><br></div></div>");

  }
?>
<div class="clr"></div>
<form id="commentform" method="post" action="process.php">

<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />

<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">

<input type="text" name="name" id="name" title="Name (required)" /><br />

<input type="text" name="email" id="email" title="Mail (will not be published) (required)" /><br />

<input type="text" name="url" id="url" title="Website" value="http://" /><br />

<br />
<textarea  title="Your Comment Goes Here" name="comment" id="comment"></textarea></p>

<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>

</form>
</div>
<div id="pages">

<?php
$total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS num FROM php_blog"));
$total_pages = ceil($total_results['num'] / $blog_postnumber);
if ($page > 1) {
    $prev = ($page - 1);
    echo "<a href=\"?page=$prev\">&lt;&lt;  Newer</a> ";
}
for($i = 1; $i <= $total_pages; $i++) {
    if ($page == $i) {
        echo "$i ";
    }
    else {
        echo "<a href=\"?page=$i\">$i</a> ";
    }
}
if ($page < $total_pages) {
   $next = ($page + 1);
   echo "<a href=\"?page=$next\">Older &gt;&gt;</a>";
}

?>
</div>
</div>
</div>
<!-- Sidebar Start -->
<div class="sidebar">

<!-- Item 1 -->
<div id="side-item"> 
<h2>
<a href="http://www.dailybooth.com/UltanCasey">
<img src="images/db-icon.jpg">Dailybooth
</a></h2>
<div id="side-item-content">
<center>
<img src="http://dailybooth.com/UltanCasey/latest/medium.jpg" />
</center>
</div>

</div>

<!-- Item 2 -->

<div id="side-item">
<h2><img src="images/connect.jpg" />Connect</h2>
</div>
<div id="side-item-content">
<div class="tweet-title"><p><a href="http://www.twitter.com/UltanKc">Latest Tweet:</a></p></div>
<div id="tweet">
<?php

function getTwitterStatus($userid){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=1";

function auto_link_twitter ($text)
{
    // properly formatted URLs
    $urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
    $text = preg_replace($urls, " <a href='$1'>$1</a>", $text);

    // URLs without protocols
    $text = preg_replace("/href=\"www/", "href=\"http://www", $text);

    // Twitter usernames
    $twitter = "/@([A-Za-z0-9_]+)/is";
    $text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>@$1</a>", $text);

    // Twitter hashtags
    $hashtag = "/#([A-Aa-z0-9_-]+)/is";
    $text = preg_replace ($hashtag, " <a href='http://hashtags.org/$1'>#$1</a>", $text);
    return $text;
}

$xml = simplexml_load_file($url) or die("could not connect");

       foreach($xml->status as $status){
       $text = $status->text;
       }
       echo auto_link_twitter ($text);
 }


getTwitterStatus("UltanKC");

?>
</div>
<br>
<ul>
<li id="social"><a href="#">YouTube</a></li>
<li id="social"><a href="#">Twitter</a></li>
<li id="social"><a href="#">LastFM</a></li>
<li id="social"><a href="#">Email</a></li>
</ul>

</div>
<!-- Item 2 End-->
<div id="side-item">
<h2><img src="images/archive.jpg" />Archives</h2>
</div>
<div id="archive-side">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');

$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");

while ($row = mysql_fetch_array($result)) {
    $get_year = $row['get_year'];
    $entries = $row['entries'];

    echo "<li id='tag'><a href=\"archives.php?year=" . $get_year . "\">Entries from " . $get_year . "  (" . $entries . ")<br /></a></li>";
}

$result1 = mysql_query("SELECT * FROM php_blog_categories ORDER BY category_name ASC");

while($row = mysql_fetch_array($result1)) {

    $result2 = mysql_query("SELECT COUNT(`id`) AS entries FROM php_blog WHERE category = $row[category_id]");
    $num_entries = mysql_fetch_array($result2);

    echo '<li id="tag"><a href="category.php?category=' . $row['category_id'] . '">' . $row['category_name'] . ' (' . $num_entries['entries'] . ')</a></li>';

}
?>
</div>

</div>

<div class="clr" />
</div>
<!-- Sidebar End  -->
<div id="footer">
<p> &copy; Ultan Casey 2010</p>
<p style="margin-top: -18px; float:right"><a href="index.php">Home</a> | <a href="about.php">About Me</a> | <a href="mailto:ultankc@thecompugeeks.com">Email Me</a></p>
</div>
</div>
</div>
</body>
</html>
?>

【问题讨论】:

    标签: php title


    【解决方案1】:

    这是我使用的方法(类似的东西,不仅仅是标题):

    <?
    ob_start (); // Buffer output
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    
    <head>
    <title><!--TITLE--></title>
    </head>
    
    <body>
    <?
    $pageTitle = 'Title of Page'; // Call this in your pages' files to define the page title
    ?>
    </body>
    </html>
    <?
    $pageContents = ob_get_contents (); // Get all the page's HTML into a string
    ob_end_clean (); // Wipe the buffer
    
    // Replace <!--TITLE--> with $pageTitle variable contents, and print the HTML
    echo str_replace ('<!--TITLE-->', $pageTitle, $pageContents);
    ?>
    

    PHP 通常可以执行任何代码并将所有输出直接打印到浏览器。如果你说"echo 'Some text here.';",该字符串将被发送到浏览器并从内存中清空。

    输出缓冲的作用是说“将所有输出打印到缓冲区。坚持下去。在我告诉你之前不要向浏览器发送任何内容。”

    所以它的作用是将所有页面的 HTML 缓冲到缓冲区中,然后在最后,在标记之后,它使用 ob_get_contents () 来获取缓冲区的内容(通常是页面的所有 HTML 源已经发送给浏览器的代码)并将其放入字符串中。

    ob_end_clean () 清空缓冲区并释放一些内存。我们不再需要源代码,因为我们只是将它存储在 $pageContents 中。

    然后,最后,我在页面的源代码 ($pageContents) 上对任何 '' 实例进行简单的查找和替换,并将它们替换为 $pageTitle 变量设置的任何值。当然,它会将&lt;title&gt;&lt;!--TITLE--&gt;&lt;/title&gt; 替换为您的页面标题。之后,我回显 $pageContents,就像浏览器一样。

    它有效地保留输出,因此您可以在将其发送到浏览器之前对其进行操作。

    希望我的 cmets 足够清晰。 如果您想确切地知道它是如何工作的(并且您应该),请在 php 手册(http://php.net/ob_start)中查找 ob_start () :)

    【讨论】:

    • 既然你已经经历了所有这些麻烦,为什么不简单地使用模板引擎,比如 Smarty?
    • 像魅力一样工作。谢谢
    【解决方案2】:

    您像往常一样从数据库中解析字段。

    那么假设你把它放在一个名为$title的变量中,你只是

    <html>
    <head>
    <title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
    </head>
    

    编辑:

    我看到了你的问题。您必须在使用之前设置$title。也就是你应该在&lt;title&gt;...之前查询数据库

    【讨论】:

    • 当我尝试“Ultan.me -”之后的区域为空白时。我没有在文档的开头打开 PHP。我应该吗?
    • 短标签是一种奇怪的做法
    • zerkms 想说的是,你应该使用 而不是
    • @Matt Williamsonah,现在我明白了。顺便说一句,我不知道。
    【解决方案3】:

    使用类似的东西怎么样:

    <?php 
        $page_title = "Your page tile";
        include("navigation.php");             // if required
        echo("<title>$page_title</title>");
    ?>
    

    【讨论】:

    • 这对我有用,只是 echo "&lt;tittle&gt;YadaYadaYada&lt;/title&gt;" 这正是我需要让原始页面/选项卡在我的浏览器上脱颖而出的一种简单方法,即使它们没有任何 html .
    【解决方案4】:

    header.php 将标题标签设置为&lt;title&gt;%TITLE%&lt;/title&gt;;,“%”很重要,因为几乎没有人输入 %TITLE%,因此您可以稍后将其用于 str_replace()。然后,你像这样使用输出缓冲区

    <?php
    ob_start();
    include("header.php");
    $buffer=ob_get_contents();
    ob_end_clean();
    $buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
    echo $buffer;
    ?>
    

    更多参考,请点击PHP - how to change title of the page AFTER including header.php?

    【讨论】:

      【解决方案5】:

      将数据检索移到脚本顶部,然后使用:

      <title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>
      

      【讨论】:

      • 当我尝试“Ultan.me -”之后的区域为空白时。我没有在文档的开头打开 PHP。我应该吗?
      • @klez:所以?他会自己想出来的。
      • @ThatMacLad:我们不明白你的意思。尝试更详细。
      • @ThatMacLad:你必须学习如何编程或雇用某人来做这件事。没有其他选择。
      • 您的年龄不是理由。如果您正在学习 - 然后尝试学习简单的代码示例,如果您正在工作 - 那么问题是您有一个您一无所知的工作
      【解决方案6】:

      您需要在回显之前设置$title 的值。

      此外,您应该在查询中使用任何数据之前对其进行真正的清理,因为这是一个安全风险

      【讨论】:

        【解决方案7】:

        创建一个新页面php并添加以下代码:

        <?php
        function ch_title($title){
            $output = ob_get_contents();
            if ( ob_get_length() > 0) { ob_end_clean(); }
            $patterns = array("/<title>(.*?)<\/title>/");
            $replacements = array("<title>$title</title>");
            $output = preg_replace($patterns, $replacements,$output);
            echo $output;
        }
        ?>

        &lt;head&gt; 添加代码:&lt;?php require 'page.php' ?&gt; 并在每个页面上调用函数ch_title('my title');

        【讨论】:

          【解决方案8】:

          问题是$title 在第 58 行被分配之前在第 5 行被引用。重新排列代码并不容易,因为数据是同时检索和输出的。只是为了测试一下,something like this work?如何

          因为您只检索一行,所以不需要使用 while 循环,但我希望它能让您更轻松地与当前代码相关联。我所做的只是从您的数据检索中删除了实际输出,并为类别和类别名称添加了变量,这些变量随后将照常引用。另外,我还没有测试过这个。 :)

          【讨论】:

            【解决方案9】:

            重新排列代码以使其正常工作会很棘手,但我会尝试 :)

            所以,把它放在代码的顶部:

            <?php require_once('mysql.php'); ?>
            

            文件的顶部应如下所示:

            <?php require_once('mysql.php'); ?>
            <html>
                <head>
            
                <meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
                <title>Ultan.me - <?php echo htmlspecialchars($title); ?> </title>
            

            然后,在包含您引用的代码的文件所在的同一目录中创建一个名为 mysql.php 的文件。

            把这是mysql.php:

            <?php
            mysql_connect ('localhost', 'root', 'root');
            mysql_select_db ('ultankc');
            
            if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
                die("Invalid ID specified.");
            }
            
            $id = (int)$_GET['id'];
            $sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";
            
            $result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" .       $sql . "<br />" . mysql_error());
            
            $res = mysql_fetch_assoc($result); 
            
            $date = date("l F d Y", $res['timestamp']);
            $title = $res['title'];
            $entry = $res['entry'];
            $get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $res['category']");
            $category = mysql_fetch_array($get_categories);
            
            ?>
            

            嗯,希望对你有所帮助:)

            【讨论】:

              【解决方案10】:

              我知道这是一篇旧文章,但读过这篇文章后,我认为这个解决方案要简单得多(尽管从技术上讲,它解决了 Javascript 而不是 PHP 的问题)。

                  <html>
                  <head>
                  <title>Ultan.me - Unset</title>
                  <script type="text/javascript">
                      function setTitle( text ) {
                          document.title = text;
                      }
                  </script>
                  <!-- other head info -->
                  </head>
              
                  <?php 
                  // Make the call to the DB to get the title text. See OP post for example
                  $title_text = "Ultan.me - DB Title";
              
                  // Use body onload to set the title of the page
                  print "<body onload=\"setTitle( '$title_text' )\"   >";
              
                  // Rest of your code here
                  print "<p>Either use php to print stuff</p>";
                  ?>
                  <p>or just drop in and out of php</p>
                  <?php
              
                  // close the html page
                  print "</body></html>";
                  ?>
              

              【讨论】:

                【解决方案11】:

                只需在 require 函数前添加 $title 变量

                <?php
                    $title = "Your title goes here";
                    require("header.php");
                  ?>
                

                header.php

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

                【讨论】:

                  【解决方案12】:
                  <?php echo APP_TITLE?> - <?php echo $page_title;?> 
                  

                  这应该适合你

                  【讨论】:

                    【解决方案13】:

                    如果你想将当前脚本文件名作为你的标题标签

                    在您的项目中包含该函数

                    function setTitle($requestUri)
                             {
                                $explodeRequestUri = explode("/", $requestUri);
                                $currentFileName = end($explodeRequestUri);
                                $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $currentFileName);
                                $explodeCurrentFileName = explode("-", $withoutExt);
                                foreach ($explodeCurrentFileName as $curFileValue) 
                                {
                                   $fileArrayName[] = ucfirst($curFileValue);
                                }
                                echo implode(" ", $fileArrayName);
                    
                             }
                    

                    并在您的 html 中包含函数脚本 并用这个替换你的标题标签

                    <title>Your Project Name -
                                <?php setTitle($_SERVER['REQUEST_URI']); ?>
                            </title>
                    

                    它适用于 php7 及更高版本,但我对 php 5 没有任何想法。* 希望对你有帮助

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-07-11
                      • 2018-10-04
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-02-19
                      相关资源
                      最近更新 更多