Search code examples
phpoutput-buffering

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


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?


Solution

  • 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);
    
    
    ?>