Move Style From PHP to Head

后端 未结 1 1932
执念已碎
执念已碎 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:

    
    

    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: