将样式从PHP移动到头部

时间:2014-06-08 20:43:47

标签: php html css

我有一个HTML页面,正文所做的第一件事就是包含顶部横幅div和导航栏div:

主html文件的正文:

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

每个包含的结构都相同,一个div和样式:

<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>

我遇到了无格式内容闪烁的问题,我认为这是因为上面的<style>标签不在<head>中,但我真的希望尽可能保持样式这些PHP文件,是否有任何方法可以正确地加载样式?

1 个答案:

答案 0 :(得分:2)

是的,它适用于输出缓冲和HTML标准。

首先,您需要启用输出缓冲:

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

然后当你完成时(在脚本的末尾),你回读缓冲区,解析HTML并将body标签中的样式元素移动到头部:

$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();

然后根据您的更改输出HTML:

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

            ...

希望这有帮助。

相关问题