Cole
Cole

Reputation: 459

Update Title for Dynamic Pages

Code:

     <html>
        <head>
        <title><?php echo $title; ?></title>
        </head>
        <body>
        <?php
            }if($_GET['page'] == 'Post'){
$title = "Post";
    ?>
    <div id = "contents">
    Post
    </div>

    <?php
            }else{
    ?>
        <div id = "contents">
$title = "Bla Bla Bla";
        Bla Bla Bla
        </div>
    <?php
            }
        }
    ?>
        </body>
        </html>

I know I can't define the variable after the head but I don't know what to do. I want this to be done using a single PHP file. If this way is not possible, what are the other ways? Lets say I also want to change the Meta contents for each dynamic page, what do I do? I also want this to be SEO friendly. How is it done?

Upvotes: 0

Views: 266

Answers (4)

selam
selam

Reputation: 54

<?php ob_start(); /* open output buffer */ ?>
<html>
  <head><title>{title}</title></head>
[php/html code]
<?php
   $response = ob_get_clean(); /* get output buffer and clean */
   $metas = array('{title}' => $title, '{description}' => $description); 
   $response = strstr($response, '{title}', $title); 
   echo $response;

Or use smarty or any other template engines.

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

Do it as below.

<?php
 $title = isset($_GET['page']) ? $_GET['page'] : 'normal heading';
?>

<html>
  <head><title><?=$title?></title></head>
</html>

Define variable before HTML code.

Upvotes: 0

Sirko
Sirko

Reputation: 74106

How about some reordering and using one more variable like this:

<?php
  if($_GET['page'] == 'Post'){
    $title = 'Post'
    $content= '<div id = "contents">Post</div>';
  } else {
    $title = 'Bla Bla Bla';
    $content = '<div id = "contents">Bla Bla Bla</div>';
  }
?>
<html>
<head>
  <title><?php echo $title; ?></title>
</head>
<body>
  <?php echo $content; ?>
</body>
</html>

That way you split your page into computation (the upper PHP part), where also headers can be send. And the output in the lower part. Makes (in my opinion) for a much clearer structure.

Upvotes: 1

Niek van der Steen
Niek van der Steen

Reputation: 1433

You can simply add the same if-statement a few lines higher too..

So your code would look like, i.e.:

<html>
    <head>
        <?php if(..your condition) { ?>
            <title>Show correct title>
        <?php } else { ?>
            <title>Other title, maybe with some meta tags..</title>
        <?php } ?>
    </head>

    <body>
        <?php if(..and the same condition again) { ?>
            <h1> And thus, it is the same condition </h1>
        <?php } ?>
    </body>
</html>

I hope you understand what I am saying ;-)

edit : Note that I do not "agree" on the design of this piece of software. Or maybe, lack of design. It's just the simple answer to the simple question ;-)

Upvotes: 1

Related Questions