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!!
Is it possible?
$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.