Forum Moderators: coopster

Message Too Old, No Replies

Updating the title of a page with PHP

Updating the page title multiple times.

         

dcelasun

7:24 am on Aug 11, 2008 (gmt 0)

10+ Year Member



Here's what I want to do:

First I have parent.php:

// Some stuff
$title ='Foo';
echo '<title>'.$title.'</title>';

switch($something) {
case 1: include ('some/other/thing.php'); break;
case 2: include ('another/thing.php'); break;

}


Now, in /some/other/thing.php:
$title = 'Bar';

Now, what I need is some sort of output buffering, so the script will check if $title is redefined somewhere and if so, it'll update the title. In this case I want the title to be changed from "Foo" to "Bar".

Any ideas?

dcelasun

8:15 am on Aug 11, 2008 (gmt 0)

10+ Year Member



Ok I've found a way. It's quite hard to find this on the web, so I'm writing it here for reference.

Include the following function in your page:

function changeTitle($new_title) {
$output = ob_get_contents();
ob_end_clean();

$output = preg_replace("/<title>(.*?)<\/title>/", "<title>$new_title</title>", $output);
echo $output;
}

In the page you want to use this, place ob_start(); at the very beginning than in anywhere in your page use changeTitle('new title'); to update the title.