Search code examples
phpcssinlinedomdocument

DomDocument inserting CSS from file in style element


I am building a system where the requirement says no links to CSS are allowed. They do allow to place all CSS content within the style element. I am using DOMDocument to build the XML/XHTML.

The CSS stylesheets are around 320 lines so I would pefer to construct them in separate CSS files and solve the insertion of the CSS content in the DomDocument build.

Question: What is the best way of inserting an external CSS file content and get it in place between the DOMDocument built style element?

Index.php

<?php

$xml = new DomDocument('1.0', 'UTF-8');
$xml->formatOutput = true;

$html = $xml->createElement('html');
$xml->appendChild($html);

$head = $xml->createElement('head');
$html->appendChild($head);
//
$style = $xml->createElement(
  'style',
  'css-content....' // The CSS content from external file should be inserted here.
);
$style->setAttribute('type', 'text/css');
$head->appendChild($style);

echo $xml->saveXML();

Main.css

  body {
    background-color: pink;
  }

Wanted result

<?xml version="1.0" encoding="UTF-8"?>
<html>
  <head>

    <style type="text/css"> 

    body {
      background-color: pink;
    }

    </style>

  </head>
</html>

Solution

  • Try something along these lines:

    Add

    $css = file_get_contents('main.css');
    

    and change $style to:

    $style = $xml->createElement('style', $css);
    

    and it should work.