Перемещение стиля с PHP на голову

У меня есть 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 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, есть ли какие-либо способ сделать стиль загрузки в голове правильно?

Да, есть, он работает с буферизацией вывода и стандартом 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 и переместите элементы стиля из тега тела в голову:

 $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; ... 

Надеюсь это поможет.