2010-08-11 17 views
5

Deseo establecer el título de mi página web en Ultan.me - Cualquiera que sea el título de la publicación. Quiero que muestre el título de la publicación. Las publicaciones se envían a una base de datos MySQL y la fila del título se llama "título". Cualquier ayuda es apreciada con esta pequeña pregunta.Establecer título de página usando PHP

Actualización:

Aquí está la página en sí ahora, pero no muestra el título. ¿Debo abrir el documento php y conectarme a mi base de datos en algún lugar diferente a sus ubicaciones actuales?

El Código (La única pieza necesaria es el comienzo):

<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:[email protected]">Email Me</a></p> 
</div> 
</div> 
</div> 
</body> 
</html> 
?> 
+3

1 para pesca de arrastre. – Frankie

Respuesta

2

Mover la recuperación de datos en la parte superior del guión, y después de que el uso:

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

Olvidó "Ultan.me" –

+0

Cuando intento que el área después de "Ultan.me -" esté en blanco.No abrí el PHP al principio del documento. ¿Debería? –

+0

@klez: ¿entonces? él mismo pensará en esto. – zerkms

7

Se analiza el campo de la base de datos como de costumbre.

Entonces digamos que pones en una variable llamada $title, sólo

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

EDIT:

veo su problema. Debe configurar $title ANTES de usarlo. Es decir, debe consultar la base de datos antes de <title>...

+0

Cuando intento que el área después de "Ultan.me -" esté en blanco. No abrí el PHP al principio del documento. ¿Debería? –

+6

etiquetas cortas es una práctica extraña – zerkms

+0

Lo que está tratando de decir zerkms, ¿debería utilizar En lugar de

1

El problema es que $title se hace referencia en la línea 5 antes de que se asigne en la línea 58. Reordenar el código no es fácil, porque los datos se recuperan y se envían a al mismo tiempo. Solo para probar, ¿cómo funciona something like this work?

Como solo está recuperando una fila, no necesita utilizar un ciclo while, pero lo dejé con la esperanza de que le sea más fácil relacionarse con su código actual Todo lo que he hecho es eliminar la salida real de la recuperación de datos y agregar variables para la categoría y el nombre de la categoría, que luego se denominarán habituales. Además, no he probado esto. :)

1

Va a ser complicado para reorganizar su código para hacer este trabajo, pero lo intentaré :)

Por lo tanto, poner esto en la parte superior de su código:

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

El parte superior del archivo debe ser similar:

<?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> 

a continuación, crear un archivo llamado mysql.php en el mismo directorio que el archivo que contiene el código que citan es en

.

Ponga esto es 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); 

?> 

Bueno, la esperanza de que ayudó a :)

21

Este es el método que utilizo (por cosas similares, no sólo título):

<? 
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 generalmente funciona ejecutando cualquier fragmento de código e imprimiendo todos los resultados directamente en el navegador.Si dices "echo 'Some text here.';", esa cadena se enviará al navegador y se vacía de la memoria.

Lo que hace el buffering de salida es decir "Imprime todos los resultados en un búfer. Espera. No envíes NINGUNO al navegador hasta que yo te diga".

Lo que hace es almacenar el HTML de todas sus páginas en el búfer, luego, al final, después de la etiqueta, usa ob_get_contents() para obtener el contenido del búfer (que generalmente es el HTML de toda la página) código fuente que ya habría sido enviado al navegador) y lo pone en una cadena.

ob_end_clean() vacía el búfer y libera algo de memoria. Ya no necesitamos el código fuente porque lo almacenamos en $ pageContents.

Luego, por último, hago un simple hallazgo &, reemplace en el código fuente de su página ($ pageContents) por cualquier instancia de '' y reemplácelos a lo que sea que la variable $ pageTitle se haya configurado. Por supuesto, reemplazará <title><!--TITLE--></title> con el título de su página. Después de eso, repito los $ pageContents, tal como lo haría el navegador.

Mantiene de forma efectiva la salida para que pueda manipularla antes de enviarla al navegador.

Afortunadamente mis comentarios son lo suficientemente claros. Busque ob_start() en el manual de PHP (http://php.net/ob_start) si usted quiere saber exactamente cómo funciona (y debe) :)

+1

Ya que está pasando por todos estos problemas de todos modos, ¿por qué no simplemente usar un motor de plantillas, como Smarty? – Brad

+0

Funciona como un encanto. Gracias –

2

Es necesario configurar el valor de $title antes eco de ella.

También, que realmente debe desinfectar todos los datos antes de usarlo en las consultas ya que esto puede suponer un riesgo

0
<?php echo APP_TITLE?> - <?php echo $page_title;?> 

esto debería funcionar bien para que

1

Sé que esto es una entrada antigua, pero después de leer esto creo que esta solución es mucho más simple (aunque técnicamente resuelve el problema con Javascript, no con 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>"; 
    ?> 
2

header.php tiene la etiqueta del título establecido en el <title>%TITLE%</title>; "%" son importantes ya que apenas tipos nadie% TÍTULO% así que se puede utilizar para que str_replace() más tarde. a continuación, se utiliza el búfer de salida al igual que

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

Para mayor referencia, haga clic PHP - how to change title of the page AFTER including header.php?

1

¿Qué hay de usar algo como:

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

crear un nuevo php página y añadir este código:

<?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; 
 
} 
 
?>

en <head> código de complemento: <?php require 'page.php' ?> y en cada página se llama a la función ch_title('my title');

Cuestiones relacionadas