How can I append a code to <head> using PHP?

10,538

You may include header.php like this:

<?php 

ob_start();
include("header.php"); 
$contents = ob_get_contents();
ob_end_clean();

echo str_replace('</head>', '<script type="text/javascript" src="js/another_script.js"></script></head>', $contents)

?>

Code is simple. You get contents of header.php to buffer, than add before of </head> new script include and print this new content to browser.

Share:
10,538
Peter
Author by

Peter

Updated on June 04, 2022

Comments

  • Peter
    Peter almost 2 years

    I've got a little web project where all pages have a common header file they import before the actual page content. The header file is something like the following:

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <script type="text/javascript" src="js/some_script.js"></script>
        <link rel="shortcut icon" href="images/web.ico" />
    </head>
    

    Then all the pages have a <?php include("header.php"); ?>, so they load the <head> tags at the begining.

    I'm now coding a new page, that also includes the previous header.php, but it requires a second javascript to load. I can load it without issues using the <script> tag in the middle of the page, but I was wondering if its possible to append it directly to the <head> tag, instead of resting in the middle of the html code.

    The actual code looks like something like this:

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" type="text/css" href="css/style.css" />
            <script type="text/javascript" src="js/some_script.js"></script>
            <link rel="shortcut icon" href="images/web.ico" />
        </head>
        <body>
            <p>Some text here</p>
            <script type="text/javascript" src="js/another_script.js"></script>
            <p>Some more text</p>
        </body>
    </html>
    

    And I would like to know how to achieve the following:

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" type="text/css" href="css/style.css" />
            <script type="text/javascript" src="js/some_script.js"></script>
            <link rel="shortcut icon" href="images/web.ico" />
            <script type="text/javascript" src="js/another_script.js"></script>
        </head>
        <body>
            <p>Some text here</p>
            <p>Some more text</p>
        </body>
    </html>
    

    I know this is possible using for example jQuery or the Simple HTML DOM, but I was wondering if I can achieve this without using any other external source.