Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding style tags to head with PHP DOMDocument

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?

like image 813
apparatix Avatar asked Dec 12 '22 22:12

apparatix


1 Answers

getElementsByTagName returns an array of nodes, so probably try

 $head->[0]->appendChild($new_elm);
like image 51
anjalis Avatar answered Dec 21 '22 23:12

anjalis