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

2.8k views Asked by At

Page.php

<?ob_start():
include('header.php');
?>

<? $pageTitle='Page';
echo 'body html';
?>

<?
$pg=ob_get_contents();
ob_end_clean();
echo str_replace('<!--TITLE-->',$pageTitle,$pg);
?>

header.php

<!-- Basic -->
<title><!--TITLE--> | DEMO</title>
<!-- Page Description and Author -->
<meta name="description" content="">
<meta name="author" content="">

How do I include the meta description content and author content with other meta name in my page.php after inserting the header.php file at the top of the page?

4

There are 4 answers

1
Mohammad Alabed On BEST ANSWER

if you do not like to modify the header file .. you can do the following ... but i advice you to make your code structure better than this :( it need to be more dynamic

<?php

ob_start();
include('header.php');
$pageTitle='Page';
echo 'body html';
$pg=ob_get_contents();


$description = 'your description';
$author = 'your author';



//delete old desc and author
$pg = str_replace('content=""', '', $pg);
//add anew desc and author
$pg = str_replace('name="description"', 'name="description" content="'.$description.'" ', $pg);
$pg = str_replace('name="author"', 'name="author" content="'.$author.'" ', $pg);

ob_end_clean();
echo str_replace('<!--TITLE-->',$pageTitle,$pg);


?>
0
tobiinformatik On

So i understand that you have to php files with html content and you want to copy the meta 'description' and 'author' of 'header.php' to 'page.php'.

It is impossible to get html content by php. You can safe the meta 'description' and 'author' in a variable and write the meta in 'header.php' and get these variables to 'page.php'

header.php:

<html>
<head>
<title>DEMO</title>
<?php
$description = '...';
$author = 'me';
echo '<meta name="description" content="'.$description.'">';
echo '<meta name="author" content="'.$author.'">';

function getDescription(){
    return $description;
}
function getAuthor(){
    return $author;
}
?>
</head>
<body>...</body>
</html>

page.php:

<html>
<head>
<title>DEMO</title>
<?php
$description = getDescription();
$author = getAuthor();
echo '<meta name="description" content="'.$description.'">';
echo '<meta name="author" content="'.$author.'">';
?>
</head>
<body>...</body>
</html>
0
Okonomiyaki3000 On

Rather than using some kind of string manipulation to insert text someplace, why not structure your app so that your business logic runs first and then your template code runs after that. Figure out what you want your title and other meta data to be before you write anything out.

0
PerroVerd On

You can define a callback function in the ob_start call is documented in the Example #1 in the ob_start webpage.

function modify_header($buffer)
{
  // do your changes in $buffer here
}

ob_start(modify_header);

Anyway, I suggest some template framework to do all this kind of work