PHP - how to change title of the page AFTER including header.php?

John Stockton picture John Stockton · Oct 22, 2012 · Viewed 82.9k times · Source

page.php:

<?php
include("header.php");
$title = "TITLE";
?>

header.php:

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

i want my title to be set AFTER including the header file. Is it possible to do this? I've seen some similiar stuff on php-fusion tvs: http://docs.php-fusion.it/temi:output_handling

Answer

we.mamat picture we.mamat · Oct 22, 2012

expanding on Dainis Abols answer, and your question on output handling,

consider the following:

your header.php has the title tag set to <title>%TITLE%</title>; the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.

then, you can use output buffer like so

<?php
    ob_start();
    include("header.php");
    $buffer=ob_get_contents();
    ob_end_clean();

    $buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
    echo $buffer;
?>

and that should do it.

EDIT

I believe Guy's idea works better since it gives you a default if you need it, IE:

  • The title is now <title>Backup Title</title>
  • Code is now:
<?php
    ob_start();
    include("header.php");
    $buffer=ob_get_contents();
    ob_end_clean();

    $title = "page title";
    $buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);

    echo $buffer;
?>