Adding style tags to head with PHP DOMDocument

apparatix picture apparatix · Sep 12, 2012 · Viewed 8.2k times · Source

I want to create and add a set of <style> tags to the head tags of an HTML document.

I know I can start out like this:

$url_contents = file_get_contents('http://example.com');
$dom = new DOMDocument;
$dom->loadHTML($url_contents);

$new_elm = $dom->createElement('style', 'css goes here');
$elm_type_attr = $dom->createAttribute('type');
$elm_type_attr->value = 'text/css';
$new_elm->appendChild($elm_type_attr);

Now, I also know that I can add the new style tags to the HTML like this:

$dom->appendChild($ss_elm);
$dom->saveHTML();

However, this would create the following scenario:

<html>
<!--Lots of HTML here-->
</html><style type="text/css">css goes here</style>

The above is essentially pointless; the CSS is not parsed and just sits there.

I found this solution online (obviously didn't work):

$head = $dom->getElementsByTagName('head');
$head->appendChild($new_elm);
$dom->saveHTML();

Thanks for the help!!

EDIT:

Is it possible?

Answer

Patouche picture Patouche · Sep 12, 2012
$head = $dom->getElementsByTagName('head');

Return a DOMNodeList. I think it will be better to get the first element like this

 $head = $dom->getElementsByTagName('head')->item(0);

So $head will be a DOMNode object. So you can use the appendChild method.