Move Style From PHP to Head

后端 未结 1 1930
执念已碎
执念已碎 2021-01-28 07:19

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:



        
相关标签:
1条回答
  • 2021-01-28 07:53

    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.

    0 讨论(0)
提交回复
热议问题