Log in

View Full Version : Dynamic <title> tag using PHP echo



magnusdahlquist
04-16-2009, 04:03 PM
Hi guys,

I'm pretty new to the PHP game.

Can you help me explain how I can add an extended title text to this code:

<?php
if ($_GET['kw'])
{echo htmlentities($_GET['kw']);}
else
{echo ucwords("This is the default title tag!");}
?>

I want the personalized (keyword triggered) tag to present more than just the keyword, for example {echo htmlentities($_GET['kw + some extra text']);}

This was kind of hard to explain, I hope you get what I mean?

Thanks!

Schmoopy
04-16-2009, 11:16 PM
I'm not sure if I quite understand what you want, do you mean something like this:


<?php
if ($_GET['kw'])
echo htmlentities($_GET['kw']) . ' custom text here.';


else
echo ucwords("This is the default title tag!");

?>

So you want like the dynamic text to come from a variable and then static text that is appended to it?

djr33
04-17-2009, 02:55 AM
Understanding the ideas behind using PHP should solve this problem.

PHP is a system in which you can generate text, in this case html. So your php script is one that just makes source code. "echo" is the simplest method of that, and there are of course lots of other complex ways to arrive at the text (like possible interaction with a database, for example), but no matter what you do, it only generates text.

So your problem is: "How do I generate source code that looks like ___?" And your solution is to have php that outputs that text at the right place.


<title><?php echo $var; ?></title>
That is the simplest way to do what you're asking. (If you want something more complex, you could use the code in the above post, for example.)

The only real tricky part is making sure all of the calculations are complete at the point where the title is echoed. The best way (and for the most part a good idea always) is to just have all of the computational php at the top of the page then your standard html layout below with any places to echo bits, basically a template method-- calcuations at the top, layout below with a few variables of php left to be echoed once the calculations are done above.

magnusdahlquist
04-17-2009, 08:50 AM
Hi,

Yeah, exactly. I want the dynamic text to come from a variable (in this case 'kw') and then static text that is appended to it.

Can I use the code in your example to do this?

Thanks a lot guys! Really appreciate your in-deepth answers :) I'm going to hang out in this forum a lot from now on!

Magnus

Schmoopy
04-17-2009, 10:49 AM
Well yes, you'd combine djr33's code with mine, so within the title tag you'd have:


<title><?php echo $_GET['kw'] . ' - Custom text here'; ?></title>