Crizly
Crizly

Reputation: 1009

Move Style From PHP to Head

I've got a HTML page, the first thing the body does is include the top banner div and the navigation bar div:

Body for main html file:

<?php
    require_once "article_functions.php";
    include "widgets/topborder.html";
    include "widgets/banner.php";
    include "widgets/navbar.html";
?>

Each of the includes are structured the same, one div and styling:

<style type="text/css">
#banner_area {
height:30px;
width: 100%;
float:left;
background-color:#00A54D;
margin-top:0px;
}

.text {
 font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
 color:white;
 margin-left:250px;
 display:inline;
}

.icons {
float:right;
width: 30px;
height: 30px;
margin-right: 5px;
}

a.text:link {
text-decoration:none!important;
}
</style>

<div id="banner_area">
<p class="text"><a href="http://example.org"> example.org </a></p>
<img class="icons" src="http://example.org/--folder-/48x48/email.png" alt="Email button">
</div>

I'm having some problems with unstyled content flashing and I think it's because the <style> tags above are not located in the <head>, but I'd really like if possible to keep the styling in these PHP files, is there any way to make the style load in the head properly?

Upvotes: 0

Views: 477

Answers (1)

hakre
hakre

Reputation: 197767

Yes there is, it works with output buffering and the HTML standard.

First of all you need to enable output buffering:

<?php
    ob_start(); // <<== Enabling output buffering
    require_once "article_functions.php";
    include "widgets/topborder.html";
    include "widgets/banner.php";
    include "widgets/navbar.html";
?>

Then when you're done (at the end of the script), you read back in the buffer, parse the HTML and move the style elements from within the body tag into the head:

$buffer = ob_get_clean();

$doc = new DOMDocument();
$doc->loadHTML($buffer);

$head = $doc->getElementsByTagName('head')->item(0);

$xpath = new DOMXPath($doc);
foreach ($xpath->query('//body//style') as $bodyStyle) {
    $head->appendChild($bodyStyle);
}

echo $doc->saveHTML();

This will then output the HTML according to your changes:

<html><head><style type="text/css">
        #banner_area {
            height: 30px;

            ...

Hope this helps.

Upvotes: 2

Related Questions